Sunday, July 18, 2010

Insert data from gridview to database (ASP.NET)

using System;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (GridViewRow row in gvTest.Rows)
{
CheckBox box = row.FindControl("cbChecked") as CheckBox;
}
}
protected void btnCGo_Click(object sender, EventArgs e)
{
// Never give a button click event any more responsibility that capturing the click event :)
GetInformationToSave();
}

///
/// Gets the information to save.
///

protected void GetInformationToSave()
{
foreach (GridViewRow row in gvTest.Rows)
{//This condition is added since here we are inserting only the rows which are checked
CheckBox checkbox = (CheckBox)row.FindControl("cbChecked");

// Collect your information below if the checkbox is checked...
if (checkbox.Checked)
{
Label lblFirstName = (Label)row.FindControl("lblFirstName");
Label lblLastName= (Label)row.FindControl("lblLastName");

//After all your information, send to method that is responsible for saving data to databasea
SaveToDatabase(lblFirstName.Text.Trim(), lblLastName.Text.Trim());
}
}
}

///
/// Saves to database.
///

///
The first name.
/// The last name.
protected void SaveToDatabase(string firstName, string lastName)
{
// CODE HERE TO SAVE TO DATABASE. OBVIOUSLY THIS METHOD SHOULD NOT BE IN THE PAGE CODE BEHIND BUT JUST HERE
// TO DEMONSTRATE.
}
}

0 comments:

Post a Comment