find out the selected value for a gridview based on it's element value

I have created a gridview with a column of checkboxes.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Regid" DataSourceID="sds1" >

<Columns>

<asp:CommandField ShowSelectButton="True" />

<asp:BoundField DataField="LName" HeaderText="Last Name" SortExpression="LName" />

<asp:BoundField DataField="FName" HeaderText="First Name" SortExpression="FName" />

<asp:BoundField DataField="Dept" HeaderText="Department" SortExpression="Dept"/>

 

<asp:TemplateField ItemStyle-HorizontalAlign="Left" >

<AlternatingItemTemplate>

<asp:CheckBox ID="CheckBox1" runat="server" />

</AlternatingItemTemplate>

<ItemTemplate>

<asp:CheckBox ID="CheckBox1" runat="server" />

</ItemTemplate>

<HeaderTemplate>

<asp:CheckBox ID="cbSelectAll" runat="server" Text="Attended" />

</HeaderTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

And I have a button after the Gridview, when I click on that button, I would like to update using a stored procedure using the Regid for that checked row.

Protected Sub btnAttend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAttend.Click

Dim myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("RegistrationConnectionString").ConnectionString)

Dim myCommand As SqlCommandmyCommand = New SqlCommand("sp_update_attended", myConnection)

myCommand.CommandType = CommandType.StoredProcedure

For index As Integer = 0 To GridView1.Rows.Count - 1

Dim cb As CheckBox = CType(GridView1.Rows(index).FindControl("CheckBox1"), CheckBox)

If cb.Checked Then

myCommand.Parameters.Add("@Regid", SqlDbType.Int).Value = ???????????????????????

End If

myConnection.Open()

myCommand.ExecuteNonQuery()

Next

myConnection.Close()

GridView1.DataBind()

Label1.ForeColor = Drawing.Color.Green

Label1.Text = "Record(s) updated Successfully."

End Sub

I'm having trouble passing the RegID for that row to my parameter. Any help is appreciated.

0
s627y
7/1/2008 5:53:54 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

6 Replies
610 Views

Similar Articles

[PageSpeed] 1

Try this:

myCommand.Parameters.Add("@Regid", SqlDbType.Int).Value = GridView1.DataKeys(index)("Regid").ToString()


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
7/1/2008 6:09:33 PM
Thank you! Now I have another problem, which is when I run the stored procedure, it complaints about Too Many Parameters.
I realize this is because All the Checkboxes are "checkbox1", so I am trying to add multiple RegIDs at a time.

For index As Integer = 0 To GridView1.Rows.Count - 1

'Programmatically access the CheckBox from the TemplateField

Dim cb As CheckBox = CType(GridView1.Rows(index).FindControl("CheckBox1"), CheckBox)

If cb.Checked Then

attend = 1

Else

attend = 0

End If

myCommand.Parameters.Add("@Regid", SqlDbType.Int).Value = GridView1.DataKeys(index)("Regid").ToString()

myCommand.Parameters.Add("@Attended", SqlDbType.Bit).Value = attend

'Call stored procedure

myConnection.Open()

myCommand.ExecuteNonQuery()

myConnection.Close()

Next

'FormView1.Visible = False

GridView1.DataBind()

Label1.ForeColor = Drawing.Color.Green

Label1.Text = "Record(s) updated Successfully."

0
s627y
7/1/2008 6:50:53 PM

Unless your stored procedure can handle an infinite amount of parameters, you must execute your database call for each checked CheckBox.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
7/1/2008 6:57:23 PM

ecbruck:

Unless your stored procedure can handle an infinite amount of parameters, you must execute your database call for each checked CheckBox.

I understand that, but how do I execute my database call for each checked CheckBox? Because all of them have the same id, how do I get one single Datakey?

Thanks.

0
s627y
7/1/2008 7:46:59 PM

ecbruck:

myCommand.Parameters.Add("@Regid", SqlDbType.Int).Value = GridView1.DataKeys(index)("Regid").ToString()

Pass the GridViewRow.RowIndex in as the "index" in the above example, and this will get you the DataKey for that specific row.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
7/1/2008 9:54:36 PM

Thank you for your help.

I found that I had to put all the following codes inside the loop, otherwise it won't work, but it's very strange why though.

Protected Sub btnAttend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAttend.Click

Dim myConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)

Dim myCommand As SqlCommand

Dim attend As Integer

For Each gvItem As GridViewRow In GridView1.Rows

Dim cb As CheckBox = CType(GridView1.Rows(gvItem.RowIndex).FindControl("CheckBox1"), CheckBox)

If cb.Checked Then

attend = 1

Else

attend = 0

End If

myCommand = New SqlCommand("update_attend", myConnection)

myCommand.CommandType = CommandType.StoredProcedure

myConnection.Open()

myCommand.Parameters.Add(
"@Regid", SqlDbType.Int).Value = GridView1.DataKeys(gvItem.RowIndex)("Regid").ToString()

myCommand.Parameters.Add("@Attend", SqlDbType.Bit).Value = attend

' 'Call stored procedure

myCommand.ExecuteNonQuery()

myConnection.Close()

Next

GridView1.DataBind()

Label1.ForeColor = Drawing.Color.Green

Label1.Text = "Record(s) updated Successfully."

End Sub

0
s627y
7/2/2008 5:26:48 PM
Reply:

Similar Artilces:

About Today's (2005-01-07) Article 'Change the style of a column within a GridView control based on its value'
Hi I read the article, sounded interesting although I've done it several times in asp.net (vb), not in C# as this article is. I wonder what the author tries to prove with this article since you cannot run it and see what it does? Since there's some hints that it might be using the Northend database there's no sign of it in the code, thus you can't do anything. Has the author deliberatly left out the datasource so that noone will ever know what the code does? Or is it so that he never thoght of the datasource since that worked in his machine, and he thought if it does work on hi...

obtain ANY control's (textbox/dropdown) value in GridView's HeaderTemplate
Given this templated GridView column containing either Textbox's or DropDownLists......          <asp:TemplateField >              <HeaderTemplate>                      <asp:TextBox ID="TextBoxWellName" runat="server"  Visible="False" l"></asp:TextBox>           &nb...

dropdownlist's selected index value is not printing the selected value
Here iS my code .Aspx Page <asp:DropDownList ID="ddlkeyword" runat="server" Width="204px" DataTextField="Form" DataValueField="Form" OnSelectedIndexChanged="ddlkeyword_SelectedIndexChanged" >   </asp:DropDownList> <asp:Button ID="Button1" runat="server" Text="Submit" Width="110px" OnClick="Button1_Click" /> my aspx.cs protected void Page_Load(object sender, EventArgs e) { fillddlkeyword(); }protected void Page_Init(object sender, EventArgs e) { ...

Meke Control's property disabled or enabled based on another property's entered value ?
Does anyone know how to disable or enable a property in properties window based on value entered in another property?Please advise.Regards,Dimitry...

new to .net, need help setting db values from checkbox's then retrieving value to a label control
Hi, Being new to asp.net i know this possible i just can't quite get it right!  I need a page with 5 checkbox's that when submitted sets the bit values in DB fields to checked. Then i need another page that retrieves the records of the checkboxes, but instead of having the db pre-set checkboxes on the second page i want it to turn on label web controls depending on if the check box is set.. I hope that makes sense?!! Can anyone point me in the right direction or to a suitable tutorial? Thanks in advance Ben Excellent article here.http://www.heliosfx.com...

GridView: ObjectDataSource has no values to insert. Check that the 'values' dictionary contains values.
Hi, I have a grid view, bound to the following object data source: <asp:ObjectDataSource ID="_odsMySampleTable"  runat="server"  SelectMethod="OnSelectAll" TypeName="SampleObjectDataSourceController" DataObjectTypeName="MyItem" InsertMethod="OnInsertItem" ></asp:ObjectDataSource> My OnInsertItem has the following signature: [DataObjectMethod( DataObjectMethodType.Insert )]public int OnInsertItem( MyItem item ) { ... } Now when I make the following call: _odsMySampleTable.Insert(); I get the following error: Exception Details: System.InvalidOperationExceptio...

Default value for Dropdownlist that get's it's value from Database.
Hi, I am using an Object Data Souce to retrieve the value of a Dropdownlist from a table on MS SQL server 2005. I want to make a default value appear on the Dropdownlist intially, should i enter the default value into the database table or is that a better way of doing it? Any suggestions will be very much appreciated. E  No need for database just set sekected value after databingind protected void Page_Load(object sender, EventArgs e) { DataBind(); ListItem defaultItem = new ListItem("Select a Person", "-1"); th...

Control's (object's) default value??
How or where can I see an asp.net control's default value? Say, for example the Visible property for webcontrols? Would be preferable if I could quickly see it in Visual Web Developer but MSDN online documentation would also be nice. Also how can I do this in general for all .Net objects?...

Viewstate : Comparing a controls previous value to it's new value
I'd like to compare the original values of a pages web controls to their new values upon postback. The problem is I can't seem to get any values from viewstate. for example some psudocode; sub pageinit() myVar = cint(viewstate("dropdownListcontrolID")) myvar2 = cint(viewstate("textBoxControLID")) end sub This doesn't error out, but all values = 1, which cannot be the case. I must be missing something. Viewstate seems like the most logical place to look for the controls previous values. Or do you recommend I do it a different way? ...

why a string column with a '' value synchronize from ASE to ASA, in ASA it's value become ' ' with a blank in it?
"darcy.zhai" <zhaizy@e-future.com.cn> wrote in news:43967064@forums-2-dub of sybase.public.sqlanywhere.mobilink: Please try to ask your question in the _body_ of the post, not the subject line. There are many people that never really look at the subject line (like myself most of the time). > why a string column with a '' value synchronize from ASE to ASA, in > ASA it's value become ' ' with a blank in it? This has to do with nullability. First, connect to ASE via ISQL and try the same query ML is executing. What is returned? An...

dropdownlist
i have created a dropdown list that is populated from a sqlserver datasource. i have a separate sql command which uses the dropdownlist.selected value as a parameter and returns the command value to a label.  it mostly works fine but with one problem. when the page loads, the label value is null, because it doesn't seem to treat the dropdownlist default value as a selected value. when i use the dropdownlist to select a value, this is fine and the label begins to display the expected value. is there anyway I can make the default value when the page is loaded act like a manual...

binding second table's column's value to the gridview how?
Hi,Im using stored procedure like this:create proc selectimageandPosting  @uName nvarchar(256)  as  begin  select postingid,imageid,location, modelno, condition, description1,description2,years,months,days,price,negotiable,username,timeofposting from posting where username=@uName  select imageurl from productimage where id=(select imageid from posting where username=@uName)  end  which gives me right o/p in query analyzer now in asp.net code behind i've written:            con.Open()  &nbs...

Change Another Column Value based on Dropdownlist selected value while gridview onrowediting
Hi everyone. Another gridview question again. I have a gridview, with three columns, Code, Description and Action. The Code column, when I click on the Edit linkbutton on the Action column becomes a dropdown list. How can I do that when I selected a value from the dropdownlist, the value of the description on would be changed to the description corresponding to the dropdownlist? Thanks.   Hi:   From your description I think you can try: 1. Set AutoPostBack=true for your DropDownList. 2. protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) &n...

How to find a label's text value in Gridview
I have a couple of lables in a gridview and I need to access thier text values. First, the GridView's relevant columns (there are actually 12):<asp:GridView ID="GridView1" runat="server" PageSize="50" AutoGenerateColumns="False" DataKeyNames="ProductCostID" DataSourceID="dsProductCost"> <Columns> <asp:TemplateField ShowHeader="False"> <ItemStyle Width="125px" /> <ItemTemplate> <asp:Button ID="btnEdit" runat="server" CausesValidation=&qu...

Web resources about - find out the selected value for a gridview based on it's element value - asp.net.presentation-controls

Portal:Bollywood/Selected biography - Wikipedia, the free encyclopedia
Write three or four paragraphs in the text field using information from the selected notable article, you may find it useful to examine the existing ...

F8: Facebook’s FbStart Initiative Will Give Selected Developers A $30K Kick-Start
... successful applications is likely a whole lot easier with $30,000 in free tools and services to start off with, and that’s exactly what selected ...

LEGO Shop - The LEGO Technic team has selected the winner... - Facebook
The LEGO Technic team has selected the winner of the Co-Creation Challenge! LEGO will be producing a limited run of 20,000 of this stunning set.... ...

Grand Doctor Ma Selected Students-baby365 on the App Store on iTunes
Get Grand Doctor Ma Selected Students-baby365 on the App Store. See screenshots and ratings, and read customer reviews.

Selected Cheney Vice Presidential Photographs
... for photos found within these albums are Paul Morse, Karen Ballard, Kimberlee Hewitt, Shealah Craighead, and Chris Greenberg. These selected ...

[iOS Advice] How To Clarify Your Email Replies By Quoting Selected Text - YouTube
Follow me on Twitter: http://www.twitter.com/macmixing Like my Facebook page: http://www.facebook.com/macmixing RATE, COMMENT, SUBSCRIBE! :-) ...

UAE Under-19 cricketers for ACC Premier League tour of Malaysia selected - The National
Coach Aaqib Javed seeking fresh blood for senior team after missing out on World Twenty20

Animal of the Day: Lucius Has Been Selected as the U.K.’s ‘Happiest Cat’
He’s got one blue eye, one green eye and a heart of gold. British mobile phone company O2 recently held some “cat auditions” to find “the UK’s ...

Boyd Cordner selected for Kangaroos squad
Sydney Roosters stars Michael Jennings and Boyd Cordner have capped a grand-final win with selection in the Australian squad for the World Cup ...

Redlands LNP branch blood-letting after Matt McEachan pre-selected
There was more blood-letting in the seat of Redlands on the weekend when a motorcycle instructor was named LNP candidate for the embattled electorate ...

Resources last updated: 12/14/2015 3:20:29 AM