C# .NET - i want to update the vlues in grid on click of the button

Asked By rehu on 03-Jun-10 07:57 AM
i have a code below chkgrid.aspx .i have made the update button to update the data can you tell me how to do it .
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="chkgrid.aspx.cs" Inherits="chkgrid" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>VIEWING THE FLOOD DATA</title>
    <style type="text/css">
        #myform
        {
            color: #0000FF;
            height: 273px;
        }
    </style>
</head>
<body style="background-image:url('bkgm6_files/bk.gif'); color: #0000FF;">
    <form id="myform" runat="server">
 
    <asp:GridView ID="GridView2" runat="server"
        onrowdatabound="GridView2_RowDataBound" AutoGenerateColumns="False"
        onselectedindexchanged="GridView2_SelectedIndexChanged"         
        style="top: 25px; left: 19px; position: absolute; height: 162px; width: 201px; float: none;"
        onrowdeleted="GridView2_RowDeleted" onrowdeleting="GridView2_RowDeleting"
        onrowediting="Editdata" onrowupdating="GridView2_RowUpdating"  
        ShowFooter="True" BackImageUrl="~/bkgm6_files/bk.gif" EnableTheming="True"
        onload="Button1_Click">
        
        
         
            
          <PagerSettings FirstPageImageUrl="~/bkgm6_files/bk.gif" />
        
        
         
            
        <HeaderStyle BorderColor="#993300" BorderStyle="Double" />
        <FooterStyle BackColor="#FF6666" Font-Bold="True" />
        <Columns>
<asp:TemplateField HeaderText="ID" >
  <EditItemTemplate>
  <asp:TextBox ID="txtID" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ID") %>' Height="15px" Width="70px"></asp:Label>
</ItemTemplate>


</asp:TemplateField>
<asp:TemplateField HeaderText="PLACE">
 <EditItemTemplate>
  <asp:TextBox ID="txtPLACE" runat="server" Text='<%# Eval("PLACE") %>'></asp:TextBox>
</EditItemTemplate>
   <ItemTemplate>   
<asp:Label ID="Label3" runat="server" Text='<%# Bind("PLACE") %>' Height="15px" Width="100px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="DISTRICT">
<EditItemTemplate>
  <asp:TextBox ID="txtDISTRICT" runat="server" Text='<%# Eval("DISTRICT") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label4" runat="server" Text='<%# Bind("DISTRICT") %>' Height="15px" Width="100px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Highest Flood Level">
<EditItemTemplate>
  <asp:TextBox ID="txtHFL" runat="server" Text='<%# Eval("HFL") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label5" runat="server" Text='<%# Bind("HFL") %>' Height="15px" Width="50px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="YEAR">
<EditItemTemplate>
  <asp:TextBox ID="txtHFL_YEAR" runat="server" Text='<%# Eval("HFL_YEAR") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label6" runat="server" Text='<%# Bind("HFL_YEAR") %>' Height="15px" Width="50px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="DANGER LEVEL">
<EditItemTemplate>
  <asp:TextBox ID="txtDANGER_LEVEL" runat="server" Text='<%# Eval("DANGER_LEVEL") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label7" runat="server" Text='<%# Bind("DANGER_LEVEL") %>' Height="15px" Width="50px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Average Water Level">
<EditItemTemplate>
  <asp:TextBox ID="txtAVG_WL" runat="server" Text='<%# Eval("AVG_WL") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label8" runat="server" Text='<%# Bind("AVG_WL") %>' Height="15px" Width="50px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="River Name">
<EditItemTemplate>
  <asp:TextBox ID="txtRIVER_NAME" runat="server" Text='<%# Eval("RIVER_NAME") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label9" runat="server" Text='<%# Bind("RIVER_NAME") %>' Height="15px" Width="80px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Water Level">
<EditItemTemplate>
  <asp:TextBox ID="txtWL" runat="server" Text='<%# Eval("WL") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label11" runat="server" Text='<%# Bind("WL") %>' Height="15px" Width="50px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
  <asp:TextBox ID="txtDATE" runat="server" Text='<%# Eval("DATE") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label12" runat="server" Text='<%# Bind("DATE") %>' Height="15px" Width="100px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="RF">
<EditItemTemplate>
  <asp:TextBox ID="txtRF" runat="server" Text='<%# Eval("RF") %>'></asp:TextBox>
</EditItemTemplate>
  <ItemTemplate>   
<asp:Label ID="Label13" runat="server" Text='<%# Bind("RF") %>' Height="15px" Width="50px"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<EditItemTemplate>
<asp:Button ID="update" Text="update" runat=server onclick="update_click" CommandName="update"  />
<asp:Button ID="cancel" text="cancel" runat=server CommandName="cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="edit" Text="edit" runat=server CommandName="edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="Delete" Text="Delete" runat=server CommandName="delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
    </asp:GridView>
    </form>
</body>
</html>


chkgrid.aspx.cs code id below



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class chkgrid: System.Web.UI.Page
{
    FloodCls flood = new FloodCls();
    System.Data.SqlClient.SqlConnection con = null;
    //System.Data.SqlClient.SqlConnection con1 = null;
    System.Data.SqlClient.SqlCommand cmd = null;
    System.Data.SqlClient.SqlDataReader rd = null;
    System.Data.SqlClient.SqlDataAdapter da = null;
    System.Data.DataSet ds = null;
    
    
    protected void Page_Load(object sender, EventArgs f)
    {
        con = new System.Data.SqlClient.SqlConnection("server=192.168.152.215;uid=sa;" +
                        "pwd=rs24;database=flood");
        if (!IsPostBack)
        {
            viewdata();
        }

    }
    private void viewdata()
    {
          
            //con.Open();
            cmd = new System.Data.SqlClient.SqlCommand("SELECT a.ID,a.PLACE,a.DISTRICT,a.HFL,a.HFL_year,a.DANGER_LEVEL,a.AVG_WL,a.RIVER_NAME,b.WL,B.DATE,B.RF  FROM flooddata1 a ,flooddata2 b where a.ID=b.ID", con);
            con.Open();
          //  TextBox1.Text = GridView1.Rows.Count.toString() + " registro(s) encontrado(s).";
            //rd = cmd.ExecuteReader();
            da = new System.Data.SqlClient.SqlDataAdapter(cmd);
            ds = new DataSet();
            da.Fill(ds);           
            GridView2.DataSource = ds;
            GridView2.DataBind();            
            con.Close();
    }
    //private void FillfloodInGrid()
    //{
    //    DataTable dtflood = flood.Fetch();

    //    if (dtflood.Rows.Count > 0)
    //    {
    //         GridView2.DataSource = dtflood;
    //         GridView2.DataBind();
    //    }
    //    else
    //    {
    //        dtflood.Rows.Add(dtflood.NewRow());
    //         GridView2.DataSource = dtflood;
    //         GridView2.DataBind();

    //        int TotalColumns =  GridView2.Rows[0].Cells.Count;
    //         GridView2.Rows[0].Cells.Clear();
    //         GridView2.Rows[0].Cells.Add(new TableCell());
    //         GridView2.Rows[0].Cells[0].ColumnSpan = TotalColumns;
    //         GridView2.Rows[0].Cells[0].Text = "No Record Found";
    //    }
    //}
     
   
   
    protected void Editdata(object s, GridViewEditEventArgs e)
    {

        GridView2.EditIndex = e.NewEditIndex;
        viewdata();// for Sql data
       
    }
    //protected void Updatedata(object sender, GridViewUpdateEventArgs e)
    //{
    //    //string place,id;
    //    //place = txtPLACE.Text;
    //    //id = txtID.text;

    //    ////salary = int.Parse(txtSalary.Text);
    //    //con = new System.Data.SqlClient.SqlConnection("server=192.168.152.215;uid=sa;" +
    //    //                      "pwd=rs24;database=flood");
    //    //con.Open();
    //    //SqlCommand cmd = new SqlCommand("update flooddata1 set place=@place where id=@id", con);
    //    ////cmd.Parameters.Add(new SqlParameter("@name", name));
    //    ////cmd.Parameters.Add(new SqlParameter("@salary", salary));
    //    ////cmd.Parameters.Add(new SqlParameter("@id", id));
    //    //cmd.ExecuteNonQuery();
    //    //con.Close();

    //    //GridView2.EditIndex = -1;

    //}

    protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {

    }
    
 
    protected void Button1_Click(object sender, EventArgs e)
    {

        //e.Row.BackColor = System.Drawing.Color.yellow;
    }

    protected void update_click(object sender, EventArgs e)
    {
       
     //  string val1 = TextID.Text;
        //drValues["Value2"] = TextPLACE.Text;
        
        int i = GridView2.Rows.Count;
        Response.Write("rids1" +i);
        //DataTable dt = ds.Tables();
        //for (int count = 0; count < i; count++)
        //{
        //    String id = dt.Rows[count];
        //}
        ////String id=dt.Rows[e.Row.RowIndex]["ID"];
        //Response.Write("rids1" + id);
       // GridView12.DataBind();
        //for (int count = 0; count < GridView2.Rows.Count; count++)
        //{

        //    //you can get the bound filed values like

        //    string strId = GridView2.Rows[count].Cell[0].Text;

        //    //to get the template field value
        //    TextBox tx1 = (TextBox)GridView2.Rows[count].FindControl("txtID");
        //    string str1 = tx1.Text;
        //    Response.Write("rids1" +str1);

        //    //you can insert the values here
        //}
       

    }
    
    protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DataTable dt = ds.Tables[0];
        if ((e.Row.RowIndex >= 0)&&(dt.Rows[e.Row.RowIndex]["DANGER_LEVEL"].ToString() != "") && (dt.Rows[e.Row.RowIndex]["WL"].ToString() != "") && (dt.Rows[e.Row.RowIndex]["WL"].ToString() != "-"))
        {
            double val1 = double.Parse(dt.Rows[e.Row.RowIndex]["DANGER_LEVEL"].ToString());
            double val2 = double.Parse(dt.Rows[e.Row.RowIndex]["WL"].ToString());
            if (val1 < val2)
            {
                //GridView2.Rows[e.Row.RowIndex].BackColor = System.Drawing.Color.Red;
                e.Row.BackColor = System.Drawing.Color.Red;
            }
        }
    }
    protected void GridView2_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {

    }
    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        //flooddata1.Delete(GridView2.DataKeys[e.RowIndex].Values[0].ToString());
        //flooddata2.Delete(GridView2.DataKeys[e.RowIndex].Values[0].ToString());
        //FillfloodInGrid();
    }
    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    //    con.Open();
    //    DataTable dt = ds.Tables[0];
    //    String val1 =dt.Rows[e.Row.RowIndex]["ID"];
    //    String val2 = dt.Rows[e.Row.RowIndex]["PLACE"];
    //    string sql = "UPDATE flooddata1 SET Place='" + Place + "' Where ID='" + ID + "'";
    //    con.Close();
    //    con.Dispose();


    }
    protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {

    }
    //public void Update(string ID, string Place, string District, string HFL, string HFL_Year, string Danger_Level, string AVG_WL, string River_name, string Lat, string Long, string Date, string WL, string RF)
    //{
    //    con.Open();
    //    String place = txtPLACE.text;
    //    String id = txtID.text;
    //    string sql = "UPDATE flooddata1 SET Place='" + Place + "' Where ID='" + ID + "'";
    //    //string sql2 = "UPDATE flooddata2 SET Date='" + Date + "',WL='" + WL + "', RF='" + RF + "' Where ID='" + ID + "'";
    //    //SqlConnection con = new SqlConnection("server=192.168.152.215;uid=sa;" +
    //    //                "pwd=rs24;database=flood");
    //    //con.Open();
    //    SqlCommand cmd = new SqlCommand(sql, con);
    //    //SqlCommand cmd1 = new SqlCommand(sql2, con);
    //    cmd.ExecuteNonQuery();
    //    //cmd1.ExecuteNonQuery();
    //    con.Close();
    //    con.Dispose();
    //}
}


  
Sagar P replied to rehu on 03-Jun-10 08:04 AM
You need to do it on GridView1_RowUpdating event only like this;

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["exam_moduleConnectionString"].ConnectionString);

SqlCommand cmd = new SqlCommand();

cmd.CommandText = "UPDATE quest_categories SET cat_name=@cat_name WHERE cat_id=@cat_id";

cmd.Parameters.Add("@cat_name", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;

cmd.Parameters.Add("@cat_id", SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);

cmd.Connection = con;

con.Open();

cmd.ExecuteNonQuery();

con.Close();

GridView1.EditIndex = -1;

BindData();

}

CHeck out these links which will give you total code and steps for same;

http://www.codeproject.com/KB/aspnet/InsertingWithGridView.aspx

http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-insert-edit-update-and-delete--the-ado.net-way.aspx

Devil Scorpio replied to rehu on 03-Jun-10 08:55 AM
Hi Rehu,

The following example demonstrates how to use the RowCommand event to update the price of a product when a row's button is clicked. This example has the paging functionality enabled for the GridView control and sets the CommandArgument property of the Button control to the appropriate row index.

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">


  Sub ProductsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)

    ' If multiple buttons are used in a GridView control, use the
    ' CommandName property to determine which button was clicked.
    If e.CommandName = "Increase" Then

      ' Convert the row index stored in the CommandArgument
      ' property to an Integer.
      Dim index = Convert.ToInt32(e.CommandArgument)

      ' Retrieve the row that contains the button clicked 
      ' by the user from the Rows collection.
      Dim row = ProductsGridView.Rows(index)

      ' Calculate the new price.
      Dim listPriceTextBox = CType(row.FindControl("PriceLabel"), Label)
      listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString()

      ' Update the row.
      ProductsGridView.UpdateRow(index, False)

    End If

  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView RowCommand Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>GridView RowCommand Example</h3>

      <asp:GridView id="ProductsGridView" 
        DataSourceID="ProductsDataSource"
        DataKeyNames="ProductID"
        AllowPaging="True" 
        OnRowCommand="ProductsGridView_RowCommand"
        AutoGenerateColumns="False"
        runat="server">
        <Columns>
          <asp:BoundField DataField="Name" HeaderText="Product Name" />
          <asp:BoundField DataField="ProductNumber" HeaderText="Product Number" />          
          <asp:TemplateField HeaderText="Price">
            <ItemTemplate>
              <asp:Label ID="PriceLabel" runat="server" 
                Text='<%# Bind("ListPrice") %>'>
              </asp:Label>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField>
            <ItemTemplate>                
              <asp:Button runat="server" ID="IncreaseButton"
                Text="Increase Price 5%"
                CommandName="Increase"
                CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>" />
            </ItemTemplate>
          </asp:TemplateField>
        </Columns>
      </asp:GridView>

      <!-- This example uses Microsoft SQL Server and connects    -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET  -->
      <!-- expression to retrieve the connection string value     -->
      <!-- from the Web.config file.                              -->
      <asp:SqlDataSource id="ProductsDataSource"
        SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [ListPrice] 
          FROM Production.Product 
          WHERE ListPrice &lt;&gt; 0"
        UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice 
          WHERE [ProductID] = @ProductID"
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        runat="server" />

    </form>
  </body>
</html>
Best Regards :)
rehu replied to Devil Scorpio on 07-Jun-10 12:14 AM
thnx
rehu replied to Sagar P on 07-Jun-10 12:15 AM
thnx
rehu replied to Sagar P on 08-Jun-10 01:31 AM
thank you but i tried to use this it is nor working with my code,i am new to the asp.net
I have made a gridview for displaying the data from the database.In asp page i am showing the data using <%# Bind("HFL_YEAR") %>.In edititemtemplate i have the textboxes. i have a edit button.on click of edit update and cancel  buttons are displayed .I want that on click of update button the data should get updated and u also tell me how to take the values of textboxs in example A.aspx.cs from A.aspx page page