i'm trying to edit the information of Student table using gridview in c#
but my code updates the gridview without changing the table in my sql database
I don't know where is the problem
Here is my gridview :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="S_ID" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AllowPaging="true" >
<Columns>
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp:TextBox ID="S_ID" runat="server" Text='<%# Eval("S_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("S_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="S_Name" runat="server" Text='<%# Eval("S_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("S_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="S_Email" runat="server" Text='<%# Eval("S_Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="S_Email" runat="server" Text='<%# Bind("S_Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
and this is the code behind:
protected void gvbind()
{
SqlConnection conn = new SqlConnection(@"MYCONNECTION");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT S_ID , S_Name , S_Email , B_ID FROM Student", conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt; // now assign this datatable dt to gridview as datasource
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int sUserId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("S_Name"); //give the edititem template ID
TextBox email = (TextBox)GridView1.Rows[e.RowIndex].FindControl("S_Email");
try
{
SqlConnection conn = new SqlConnection(@"MYCONNECTION");
conn.Open();
SqlCommand c = new SqlCommand("Update Student set S_Name='" + name.Text + "',S_Email='" + email.Text + "'where S_ID='" + sUserId + "'");
c.Connection = conn;
c.ExecuteNonQuery();
GridView1.EditIndex = -1;
gvbind();
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(typeof(string), "Key", "alert('Error : \\n" + ex.Message + "');", true);
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gvbind();
}
please can anyone help me why this change the gridview only but not the DB ?!