Alexander Alexander - 1 year ago 96
ASP.NET (C#) Question

how to update data in SQL from Gridview moving from one Row to another in ASP,C#

I have a grid view as below,
GridView

I want to update table based on the text entered in the text box, when the focus shifted to next row. How can I achieve that?

I have done the coding in page index changing, I'm new to web programming bit confused how to achieve that using C# in ASP.

Below is the code I've written for page index changing..

ASP

<asp:GridView ID="GVItems" runat="server"
CssClass="table table-hover table-striped table-bordered" GridLines="None"
AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="GVItems_PageIndexChanging" OnRowEditing="GVItems_RowEditing" OnSelectedIndexChanging="GVItems_SelectedIndexChanging">
<AlternatingRowStyle BackColor="#CCCCCC" BorderStyle="None" />
<Columns>
<asp:BoundField DataField="UNIQ" HeaderText="UNIQ" />
<asp:BoundField DataField="store" HeaderText="STORE" />
<asp:BoundField DataField="MQty" HeaderText="Modified Qty" />
<asp:TemplateField HeaderText="Edit MQty" >
<ItemTemplate >
<asp:TextBox ID="txtUpdatedQty" runat="server" Text="" Width="40" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle CssClass="cursor-pointer" />
<PagerStyle HorizontalAlign="Right" CssClass="pagination-ys" />
</asp:GridView>


C#

protected void GVItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
UpdateRecvQty();
GVItems.PageIndex = e.NewPageIndex;
this.BindGrid();
}
private void UpdateRecvQty()
{

foreach (GridViewRow row in GVItems.Rows)
{
if (((TextBox)row.FindControl("txtUpdatedQty")).Text != "")
{
uniqID = row.Cells[0].Text;
qty = ((TextBox)row.FindControl("txtUpdatedQty")).Text;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();

string query = "UPDATE [dbo].[Tbl_Order] SET MQty = @qty where UNIQU=@uniqID";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@qty", qty);
cmd.Parameters.AddWithValue("@uniqID", uniqID);
cmd.ExecuteNonQuery();
}
}
}

Answer Source

Why not use the textChanged event of the textbox and update the value every time the user edits the textbox instead of looping at the end?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download