Last post Jun 11, 2006 02:19 AM by Sjonnie2nd
Jun 04, 2006 11:09 AM|pettrer|LINK
I need to loop through the rows of a gridview, to insert them into a db table manually (for various reasons I can't do it automatically in this case). I can't figure out how to do this correctly, and strangely, I can't find any good
example of it on the net. Here's what I want to do:
Protected Sub Insertbutton_Click(sender... etc)
Dim insconn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
InsertCmdString = "Insert into products (fid, serie) VALUES (103, '" & SerieDropDownList.SelectedValue & "')" 'just testing values for now
Dim inscmd As SqlCommand = New SqlCommand(InsertCmdString, insconn)
Dim i As Integer = 0
Dim insrows As System.Web.UI.WebControls.GridViewRowEventArgs
While insrow(i) < insrow.Row ???
So I have two problems:
1. How do I do the looping/indexing (where I put the ???)
2. How do I get the values from the gridview to be variables that I can insert via the insertcommand?
Thanks in advance for all help.
Jun 04, 2006 07:53 PM|zeeshan.muhammad|LINK
Here's an example to iterate through each row of a gridview. You need to write code according to your requirement for extracting values and saving it into the database. You can convert the code into VB.NET and can insert it after you open a connection to
your database. GridView1 is the ID of the GridView and I suppose you may need the ID of the row to update that row in the database later on, so you will find it useful to use DataKeyNames to store and retreive ID for each row.
for (int i = 0; i < GridView1.Rows.Count; i++)
GridViewRow Row = GridView1.Rows[i];
int ID = (int)GridView1.DataKeys[e.Row.RowIndex].Value;
Hope that helps!
Jun 04, 2006 10:29 PM|cashmore|LINK
Another example in VB.net
Jun 10, 2006 11:26 PM|pettrer|LINK
Thanks a lot, both of you, for your help. I think I'll get it now. Cashmore - I see you're from UK. Not the finest day for our countries this Saturday (Sweden-Trinidad; England-Paraguay). It'll get better soon!
Jun 11, 2006 02:19 AM|Sjonnie2nd|LINK
My experience with the GridView is that the underlying data isnot allways that easy to access. Catching RowDataBound only tells you something about the current row. The dataitem of the previous rows may allready have been destroyed.
Catching DataBound (after all rows are bound) leaves you with no underlying data at all. The only thing you can do is to loop through the generated Rows and Cells and find the string representation of the data.
Possibly a better method is doing the selection yourself. Here is an example in c#:
DataView dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty) as DataView;
foreach (DataRowView drv in dv)