ASP.NET - Need to maintain checked status of check boxes inside a datagrid

Asked By Libin Emmanuel
26-Feb-11 05:40 AM
Hi Everyone,
My Datagrid has a TemplateColumn contains checkbox control and I set
its AutoPostback property to True. So that I can update database
straight after user Check the Checkbox. I am updating the database with true string on checking the checkbox.

After checking ,and on refresh of the whole page the checked status should be maintained. I want this to be done based on checking the status inside the database. If it is true inside database whenever the user login he should see its checked or immediately after checking checkbox and refreshing it should be checked itself. Please anyone help
  Jatin Prajapati replied to Libin Emmanuel
26-Feb-11 06:37 AM
Hi,
Please refer the below code example. This will give you better idea.
01.<%@ Page Language="C#" %>
02. 
03.<%@ Import Namespace="System" %>
04.<%@ Import Namespace="System.Data" %>
05.<%@ Import Namespace="System.Data.SqlClient" %>
06.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
07.<script runat="server">
08.  protected void Page_Load(object sender, EventArgs e)
09.  {
10.    if (!IsPostBack)
11.      LoadProducts();
12.  }
13. 
14.   
15.  private void LoadProducts()
16.  {
17.    using (SqlConnection connection = new SqlConnection("ConnectionString"))
18.    {
19.      using (SqlCommand command = new SqlCommand("Select * from Products", connection))
20.      {
21.        using (SqlDataAdapter da = new SqlDataAdapter(command)) {
22.          DataTable dt = new DataTable();
23.          da.Fill(dt);
24.          GridView1.DataSource = dt;
25.          GridView1.DataBind();
26.        }
27.      }
28.    }
29.  }
30. 
31.  protected void cb_CheckedChanged(object sender, EventArgs e)
32.  {
33.    using (SqlConnection connection = new SqlConnection("ConnectionString"))
34.    {
35.      using (SqlCommand command = new SqlCommand("Update products set Status=@Status where ProductName=@ProductName", connection))
36.      {
37.        command.Parameters.AddWithValue("@Status", ((CheckBox)sender).Checked.ToString());
38.        command.Parameters.AddWithValue("@ProductName", ((CheckBox)sender).Text);
39.        connection.Open();
40.        command.ExecuteNonQuery();
41.        connection.Close();
42.      }
43.    }
44.  }
45. 
46.  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
47.  {
48.    if (e.Row.RowType == DataControlRowType.DataRow)
49.    {
50.      HiddenField hd = e.Row.FindControl("hdn") as HiddenField;
51.      CheckBox cb = e.Row.FindControl("cb") as CheckBox;
52.      if (hd.Value.ToLower() == "true")
53.        cb.Checked = true;
54.      else
55.        cb.Checked = false;
56.    }
57.  }
58.</script>
59.<html xmlns="http://www.w3.org/1999/xhtml">
60.<head runat="server">
61.  <title></title>
62.</head>
63.<body>
64.  <form id="form1" runat="server">
65.  <div>
66.    <asp:ScriptManager ID="sm" runat="server">
67.    </asp:ScriptManager>     
68.    <asp:GridView ID="GridView1" runat="server"
69.      onrowdatabound="GridView1_RowDataBound">
70.      <Columns>
71.        <asp:TemplateField>
72.          <ItemTemplate>
73.            <asp:CheckBox id="cb" runat="server" AutoPostBack="true" Text='<%#Eval("ProductName") %>' OnCheckedChanged="cb_CheckedChanged" />
74.            <asp:HiddenField ID="hdn" runat="server" Value='<%#Eval("Status") %>' />
75.          </ItemTemplate>
76.        </asp:TemplateField>
77.      </Columns>
78.    </asp:GridView>
79.    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
80.      SelectCommand="SELECT [ProductID], [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock] FROM [Alphabetical list of products]">
81.    </asp:SqlDataSource>
82.  </div>
83.  </form>
84.</body>
85.</html>
  Libin Emmanuel replied to Jatin Prajapati
26-Feb-11 07:14 AM
Thanks a lot it worked....Cheers!!!
Create New Account
help
How to autorefresh a gridview In a ASP.NET page I want to refresh only a gridview in time interval of 30 secs instead of autorefresh the whole page. How to do this. . . . ??? means whats the codeto write?? plz help me out. . . . . . . advance thanks and code. http: / / asp-net-csharp-vb.blogspot.com / 2009 / 06 / auto-refresh-data-on-page-using-ajax.html Hope this helps. Could u plz send me the total code to Uid = sa; pwd = ;" ) cmd.CommandText = "select * from Employees " cmd.Connection = con con.Open() da = New SqlDataAdapter(cmd) da.Fill(ds) cmd.ExecuteNonQuery() GridData.DataSource = ds GridData.DataBind() End Sub You can check your current time on page load. Write this code: MyLabel.Text = System.DateTime.Now.ToString() BindData() and grid refresh time runat = "server"> < asp : Label ID = "Label2" runat = "server" Text = "This is Time, When The Full Page Load :" Font-Bold = "true"> < / asp : Label > &nbsp; < asp : Label ID = "MyLabel" runat = "server"> < / asp : Label asp : BoundColumn > < / Columns > < / asp : DataGrid > < / ContentTemplate > < / asp : UpdatePanel > < / form > Does this code apply to child page too??? And one thing more, I've a connection string and I don't think
first of all. i wonder wat could be the problem. anyhelp would be greatly appreciated. <%@ Page Language = "C#" AutoEventWireup = "true" CodeBehind = "Default.aspx.cs" Inherits = "WebApplication2._Default" %> <!DOCTYPE html PUBLIC "- / / W3C Data.Sql; using System.Data.SqlClient; namespace WebApplication2 { public partial class _Default : System.Web.UI.Page { Clientcls Client = new Clientcls(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillClientInGrid(); } } private ndmk.SelectedValue); FillClientInGrid(); lblMessage.Text = "New Record was Inserted Successfully"; } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType = = DataControlRowType.DataRow) { DropDownList ddOrg_type = (DropDownList)e.Row.FindControl("ddOrg_type"); if (ddOrg_type ! = null) { ddOrg_type.DataSource = Client.FetchOrg_type DataBind(); ddOrg_type.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString(); } } if (e.Row.RowType = = DataControlRowType.DataRow) { DropDownList ddClient_PartnerId = (DropDownList)e.Row.FindControl("ddClient_PartnerId"); if (ddClient_PartnerId ! = null) { ddClient_PartnerId.DataSource = Client.FetchClient_PartnerId DataBind(); ddClient_PartnerId.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString(); } } if (e.Row.RowType = = DataControlRowType.DataRow) { DropDownList ddWork_type = (DropDownList)e.Row.FindControl("ddWork_type"); if (ddWork_type ! = null) { ddWork_type.DataSource = Client.FetchWork_type DataBind(); ddWork_type.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString(); } } if (e.Row.RowType = = DataControlRowType.DataRow) { DropDownList ddMK_mailinglist = (DropDownList)e.Row.FindControl("ddMK_mailinglist"); if (ddMK_mailinglist ! = null) { ddMK_mailinglist.DataSource = Client.FetchMK_mailinglist DataBind(); ddMK_mailinglist.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString(); } } if (e.Row.RowType = = DataControlRowType.Footer) { DropDownList ddnewOrg_type = (DropDownList)e.Row.FindControl("ddnewOrg_type"); ddnewOrg_type.DataSource = Client.FetchOrg_type(); ddnewOrg_type.DataBind(); } if
for retrieving the data from tbl_orders table. SqlCommand mySqlCommand = new SqlCommand("select * from tbl_orders", mySQLconnection); SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand); DataSet myDataSet = new DataSet(); mySqlAdapter.Fill(myDataSet); / / GridView Data Control Bound to the DataSet get the data from tbl_order_status table. mySqlCommand = new SqlCommand("select * from tbl_order_status", mySQLconnection); mySqlAdapter = new SqlDataAdapter(mySqlCommand); myDataSet = new DataSet(); mySqlAdapter.Fill(myDataSet); / / DropDownList Control Object Created to bind the data WebParts; using System.Web.UI.HtmlControls; namespace Lesson4 { public partial class _Default : System.Web.UI.Page { / / Tempory Table to Store the City DataTable dtCities; protected void Page_Load(object sender, EventArgs e) { if (! Page.IsPostBack ) { / / Select the Contact name and City from the Northwind table DataTable dtTemp = (DataTable)SQLConnections DataBind(); / / Dispose dtCities.Dispose(); dtCities = null; dtTemp.Dispose(); dtTemp = null; } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { / / Handle the Gridview RowDatabound Event if(e.Row.RowType = = DataControlRowType.DataRow) { / / Check if it is a DataRow. / / Cast the row item as DatarowView DataRowView drv SQLConnections.OpenConnection(); sqlcmd.Connection = sqlCon; using (sqlCon) { if (QueryReturnType = = ReturnType.ExcuteNonQuery) { int intRowsAffected; intRowsAffected = sqlcmd.ExecuteNonQuery(); objReturn = intRowsAffected; } else if (QueryReturnType = = ReturnType.ExcuteDatatable) { SqlDataAdapter sda = new SqlDataAdapter(sqlcmd); DataTable dtTemp = new
EventArgs e) { if (!IsPostBack) { SqlConnection cn = new SqlConnection("con string"); string strQuery = "Select * from EmpImage"; SqlDataAdapter da = new SqlDataAdapter(strQuery, cn); DataSet ds = new DataSet(); da.Fill(ds); DropDownList1.DataSource = ds; DropDownList1.DataTextField = "COLUMN_NAME of DropDownList protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("con string "); SqlDataAdapter adapSel; string mySQL = "SELECT * from tablename where id = '" + DropDownList1.SelectedValue.ToString() + "'; adapSel = new SqlDataAdapter(mySQL, conn); DataSet dsSel = new DataSet(); adapSel.Fill(dsSel); Gridview .DataSource = dsSel; Gridview .DataBind(); conn to dropdownlist value and put the below code on droplown selectedIndex change event, not on page load event using (SqlConnection conn = new SqlConnection( "Your Connection string here" )) { conn.Open(); string sqlQuery = "Select * from table1 where columnName like " %+dropdown1.Text+%"; SqlCommand cmd = new SqlCommand(sqlQuery, conn) SqlDataAdapter da = New SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); gridView1.Datasource = dt; gridView1.DataBind(); } } In the SqlConnection("Data Source = 10.0.2.8;Initial Catalog = JitendraDB;User ID = sa;password = change_123"); SqlDataAdapter da; string mySQL = "SELECT empid, empname, dept FROM emp "; da = new SqlDataAdapter(mySQL, con); con
SqlCommand ( "insert into tbl_cal(name, amount, total)values('" + TextBox4.Text + "', '" + TextBox2.Text + "', '" +f+ "')" , con); cmd.ExecuteNonQuery(); TextBox2.Text = "" ; TextBox4.Text = "" ; ShowAlertMessage( "Successfully inserted" ); bindgrid(); / / CalculateRunningtotal(); } else { dr.Close(); } } else { cmd = new insert into tbl_cal(name, amount, total)values('" + TextBox4.Text + "', '" + TextBox2.Text + "', '" +TextBox2.Text+ "')" , con); cmd.ExecuteNonQuery(); TextBox2.Text = "" ; TextBox4.Text = "" ; ShowAlertMessage( "Successfully inserted" ); bindgrid(); / / CalculateRunningtotal(); } } catch ( Exception ex) { Response.Write( "Error update tbl_cal set amount = '" + txamount.Text + "', total = '" + txtotal.Text + "' where id = '" + lbid.Text + "'" , con); cmd.ExecuteNonQuery(); GridView1.EditIndex = -1; ShowAlertMessage( "Updated Successfully" ); bindgrid(); CalculateRunningtotal(); } public void CalculateRunningtotal() { int prevvalue = 0; foreach and then compute the total. See the sample code below: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { / / Initialize the running total to zero. int currentRunningTotal = 0; / / Find if the current row is a datarow, and not a header / footer. if (e.Row.RowType = = DataControlRowType.DataRow) { / / Capture this row's amount from the data. In this case, the column name to implement that you above told that codings in my codings: this is my full page codings: using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq using System.Xml.Linq; using System.Data.SqlClient; public partial class cal : System.Web.UI. Page { SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "newhotel" ].ConnectionString); SqlCommand cmd; SqlDataAdapter adap; DataSet ds; SqlDataReader dr; float total; float total1; string g; protected void Page_Load( object