ASP.net Making Unbound column invisible - c#

I'm trying to get a column in my unbound gridview to be invisible, specifically the id. I'm binding the grid with ADO.net, so I cant just set the tag in the html code to invisible. Here is some code...
protected void btn_search_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source=WILSON-PC; Initial Catalog=KamManOnline; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("SELECT oid, Supplier, DepartmentA, DepartmentB, DepartmentC, OrderNumber, CONVERT(varchar(10), PORecieptDate, 101) AS PORecieptDate, CONVERT(varchar(10), ProductRecieved, 101) AS ProductRecieved, CONVERT(varchar(10),POEntryDate, 101) AS POEntryDate FROM tbl_OrderD WHERE (Supplier = #Supplier OR #Supplier IS NULL) AND (DepartmentA = #DepartmentA OR #DepartmentA IS NULL) AND (OrderNumber = #OrderNumber OR #OrderNumber IS NULL) AND (PORecieptDate BETWEEN #FromA AND #ToA OR (#FromA IS NULL AND #ToA IS NULL)) AND (ProductRecieved BETWEEN #FromB AND #ToB OR (#FromB IS NULL AND #ToB IS NULL)) AND (POEntryDate BETWEEN #FromC AND #ToC OR (#FromC IS NULL AND #ToC IS NULL))", cs);
if (!chk_Suppliers.Checked) da.SelectCommand.Parameters.Add("#Supplier", SqlDbType.VarChar).Value = ddl_SupplierView.Text.ToString();
else da.SelectCommand.Parameters.Add("#Supplier", SqlDbType.VarChar).Value = DBNull.Value;
if (!chk_Departments.Checked) da.SelectCommand.Parameters.Add("#DepartmentA", SqlDbType.VarChar).Value = ddl_DepartmentView.Text.ToString();
else da.SelectCommand.Parameters.Add("#DepartmentA", SqlDbType.VarChar).Value = DBNull.Value;
if (txt_orderNumView.Text != "") da.SelectCommand.Parameters.Add("#OrderNumber", SqlDbType.VarChar).Value = txt_orderNumView.Text.ToString();
else da.SelectCommand.Parameters.Add("#OrderNumber", SqlDbType.VarChar).Value = DBNull.Value;
if (txt_PORecievedFrom.Text != "" && txt_PORecievedTo.Text != "")
{
da.SelectCommand.Parameters.Add("FromA", SqlDbType.SmallDateTime).Value = txt_PORecievedFrom.Text.ToString();
da.SelectCommand.Parameters.Add("ToA", SqlDbType.Date).Value = txt_PORecievedTo.Text.ToString();
}
else
{
da.SelectCommand.Parameters.Add("FromA", SqlDbType.Date).Value = DBNull.Value;
da.SelectCommand.Parameters.Add("ToA", SqlDbType.Date).Value = DBNull.Value;
}
if (txt_ProductRecievedFrom.Text != "" && txt_ProductRecievedTo.Text != "")
{
da.SelectCommand.Parameters.Add("FromB", SqlDbType.Date).Value = txt_PORecievedFrom.Text;
da.SelectCommand.Parameters.Add("ToB", SqlDbType.Date).Value = txt_PORecievedTo.Text;
}
else
{
da.SelectCommand.Parameters.Add("FromB", SqlDbType.Date).Value = DBNull.Value;
da.SelectCommand.Parameters.Add("ToB", SqlDbType.Date).Value = DBNull.Value;
}
if (txt_POEntryFrom.Text != "" && txt_poEntryTo.Text != "")
{
da.SelectCommand.Parameters.Add("FromC", SqlDbType.Date).Value = txt_PORecievedFrom.Text;
da.SelectCommand.Parameters.Add("ToC", SqlDbType.Date).Value = txt_PORecievedTo.Text;
}
else
{
da.SelectCommand.Parameters.Add("FromC", SqlDbType.Date).Value = DBNull.Value;
da.SelectCommand.Parameters.Add("ToC", SqlDbType.Date).Value = DBNull.Value;
}
ds.Clear();
da.Fill(ds);
gv_search.DataSource = ds.Tables[0];
gv_search.DataBind();
}
this is your basic good old ASP.net search function. However, in this gridview I enable selecting like this...
protected void gv_search_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("selectedOrder.aspx?oid=" + gv_search.SelectedValue.ToString());
}
I know I can set the oid to be the datakey tab. However, I want to make this invisible. I have tried this method here...
protected void gv_search_RowCreated(object sender, GridViewRowEventArgs e)
{
gv_search.Columns[0].Visible = false;
}
It gave me this error...
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Does anyone know how to do this? Thanks

Declare the columns you want displayed inside the aspx file. Tell the grid to not generate columns using the AutoGenerateColumns="False" property.
<asp:DataGrid id="DataGrid1"
runat="server" CssClass="grid"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn
DataField="OrderID" ReadOnly="True"
HeaderText="Order ID" />
<asp:BoundColumn
DataField="ShipName" HeaderText="Ship to"
ReadOnly="True" />
<asp:BoundColumn
DataField="ShipCountry" HeaderText="Country"
ReadOnly="True" />
<asp:BoundColumn
DataField="ShipCountry" HeaderText="Country"
Visible="False" />
</Columns>
</asp:DataGrid>
Set the desired columns to Visible="False".

Change it to the DataBound event:
protected void gv_search_DataBound(object sender, EventArgs e)
{
gv_search.Columns[0].Visible = false;
}

Related

Change DateFormat of dropdown inside gridview

I have a dropdown inside a asp gridview to Filter based on the selected dates. But when I make a selection on the dropdown I get an error, MySql.Data.MySqlClient.MySqlException: Incorrect date value: '9/12/2018 12:00:00 AM' for column 'dateValue' at row 1.
Below would be the client side code:
<asp:GridView ID="gdvTM" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="true" AllowPaging="true" OnPageIndexChanging="gdvTM_PageIndexChanging" DataKeyNames="ID" PageSize="10" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc" >
<Columns >
<asp:TemplateField>
<HeaderTemplate>
Date:
<asp:Label ID="lbldate" Text="date" Visible="false" runat="server"></asp:Label>
<asp:DropDownList ID="ddlgvdate" DataTextFormatString="{0:yyyy-MM-dd}" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true">
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate >
<asp:Label ID="lbldate1" runat="server" Text='<%# Eval("date", "{0:yyyy-MM-dd}") %>'></asp:Label>
</ItemTemplate>
</Columns>
</asp:GridView>
Below would be the server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindDropDownList()
{
PopulateDropDown((cells.FindControl("ddlgvdate") as DropDownList), (cells.FindControl("lbldate") as Label).Text);
}
private void PopulateDropDown(DropDownList ddl, string columnName)
{
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please Select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData1");
cmd.CommandType = CommandType.StoredProcedure;
string date = null;
DateTime dateValue1 = Convert.ToDateTime(date);
string dateValue = dateValue1.ToString("yyyy-MM-dd");
dateValue = null;
if (ViewState["Date"] != null && ViewState["Date"].ToString() != "0")
{
dateValue = ViewState["Date"].ToString();
}
cmd.Parameters.AddWithValue("dateValue", dateValue);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Date"] != null ? (string)ViewState["Date"] : string.Empty, cell.FindControl("ddlgvdate") as DropDownList);
}
private void setDropdownselectedItem(string selectedvalue, DropDownList ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
DropDownList dropdown = (DropDownList)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlgvdate":
ViewState["Date"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below would be the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetApprovedData1`
(in dateValue date)
BEGIN
SELECT *
FROM approved
WHERE
(dateValue IS NULL OR date = dateValue);
END
Please let me know how I can pass the date with the right format. Thanks in advance.
Thanks for John's suggestion I figured it out by using Nullable DateTime as shown below
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetApprovedData1");
cmd.CommandType = CommandType.StoredProcedure;
DateTime? dateValue = null;
if (ViewState["Date"] != null && ViewState["Date"].ToString() != "0")
{
dateValue = DateTime.Parse(ViewState["Date"].ToString());
}
cmd.Parameters.AddWithValue("dateValue", dateValue);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["Date"] != null ? (string)ViewState["Date"] : string.Empty, cell.FindControl("ddlgvdate") as DropDownList);
}

how to get column data when check box is checked using data list in asp.net

this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.

Make ASP Validators validate just one gridview row?

I am making a little website for myself and within this website you can make users. The moment you add a user it goes into a database. You can also see the existing users in a gridview, so when you make a new user it goes into the gridview. But one little problem, when I try and use validators within this gridview, it validates every row. I need it to validate just one row. Someone said something about row ID, but i don't know how to make that work.
As you can see I've tried some stuff with RowIndex, but couldn' t get it to work
Any help is appreciated
Management.Aspx :
<asp:GridView runat="server" ID="gridUsers" AutoGenerateColumns="False" DataKeyNames="username" DataSourceID="DSUserList" OnRowCommand="gridUsers_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="username"></asp:BoundField>
<asp:BoundField DataField="display_name" HeaderText="Naam" SortExpression="display_name"></asp:BoundField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button OnClientClick="ConfirmDeleteAdmin()" Text="Verwijderen" runat="server" id="btnDeleteUser" CommandName="delUser" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtChangePassword" />
<%-- TODO: Mike: Validators via code --%>
<asp:Button OnClientClick="ConfirmChangePassword()" ValidationGroup="vgChangePW" Text="Wachtwoord wijzigen" runat="server" ID="btnChangePassword" CommandName="changePassword" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<%-- <asp:RequiredFieldValidator ID="rfChangePassReq" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>U heeft geen nieuw wachtwoord ingevoerd"></asp:RequiredFieldValidator>--%>
<%-- asp:RegularExpressionValidator ID="rfChangePassReg" ValidationExpression="^(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>Uw wachtwoord moet uit minimaal 6 tekenen bestaan en moet minimaal 1 hoofdletter en 1 cijfer bevatten"></asp:RegularExpressionValidator>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Management.aspx.cs :
protected void btnCreateUser_Click(object sender, EventArgs e)
{
try {
connection.Open();
} catch (Exception) {}
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_add_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = txtUsername.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#displayName", SqlDbType.NVarChar, 100).Value = txtDisplayName.Text;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0)
{
lblNewUserStatus.Text = "Gebruiker bestaat al";
lblNewUserStatus.ForeColor = Color.Red;
}
else
{
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
lblNewUserStatus.Text = "Gebruiker toegevoegd";
lblNewUserStatus.ForeColor = Color.Black;
txtUsername.Text = "";
txtPassword.Text = "";
txtDisplayName.Text = "";
}
connection.Close();
}
protected void gridUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Deletes user or changes a password of a user
if (e.CommandName == "delUser")
{
string confirmValue = Request.Form["delete_admin"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String usernameToDelete = row.Cells[0].Text;
try {
connection.Open();
} catch (Exception) { }
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_delete_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = usernameToDelete;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
//Failed
lblDelteStatus.Text = "Kan gebruiker admin niet verwijderen";
lblDelteStatus.ForeColor = Color.Red;
} else {
// Deleted
lblDelteStatus.Text = "Gebruiker verwijderd";
lblDelteStatus.ForeColor = Color.Black;
// Reload user list
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
}
connection.Close();
if (usernameToDelete == Session["username"].ToString()) {
ProjectManager.logout();
Page.Response.Redirect(Page.Request.Url.ToString());
}
}
}
else if (e.CommandName == "changePassword")
{
string confirmValue = Request.Form["change_password"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String username = row.Cells[0].Text;
TextBox txtPassword = (TextBox)row.Cells[3].FindControl("txtChangePassword");
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
try {
connection.Open();
} catch (Exception) { }
cmd.Connection = connection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_change_password";
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = username;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
lblDelteStatus.Text = "Dit wachtwoord is onlangs gebruikt, kies een ander wachtwoord";
lblDelteStatus.ForeColor = Color.Red;
} else if (code == 1) {
lblDelteStatus.Text = "Wachtwoord gewijzigd";
lblDelteStatus.ForeColor = Color.Black;
}
connection.Close();
}
}
}
Try this in the RowDataBound event:
Create a row specific validation group name that is a concatenation of some prefix and the row index and assign it to each validator and control in the row that is part of the validation group... i.e.:
valGroupName = string.format("vgRow{0}", e.row.rowindex.tostring);
Button btn = e.row.FindControl("btnChangePassword");
btn.ValidationGroup = valGroupName
RequiredFieldValidator vreq = e.row.FindControl("rfChangePassReq");
vreq.ValidationGroup = valGroupName
RegularExpressionValidator vregx = e.row.FindControl("rfChangePassReg");
vregx.ValidationGroup = valGroupName
...etc...
This way only validation for the specific row should be triggered when you select the row button to save.
I don't recall and I can't test it right now, but you may have an issue with any field that is connected to a RequiredFieldValidator, it may prevent posting. You'll have to check that out. You might be ok as they will be part of a different validation group.

asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" the OnRowDeleting not working

Excuse me,
I am following this tutorial
On that tutorial, the command field using Link..
I want to use Button instead of LinkButton..
I change my code to Like this:
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true"
HeaderText="Action" ItemStyle-Width="150" />
Behind code like this:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridViewPaging.EditIndex)
{
(e.Row.Cells[3].Controls[2] as Button).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
then my OnRowDeleting method not working...
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int sales_so_id = Convert.ToInt32(GridViewPaging.DataKeys[e.RowIndex].Values[0]);
//delete operation
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("DeleteSO", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#sales_so_id", SqlDbType.Int));
cmd.Parameters["#sales_so_id"].Value = sales_so_id;
cmd.ExecuteNonQuery();
con.Close();
Getdata();
}
What should I do?
when I use LinkButton, everything is ok..
But, now the OnRowDeleting behind code is not working..
Please help.
Finally, I use this tutorial
My previous onDataBound like this:
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridViewPaging.EditIndex)
{
(e.Row.Cells[3].Controls[2] as Button).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
and I change it into this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
string item = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[3].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
}
}
}
Now it is working..
Thank you

How to keep check box checked after button click for update

Please help me to keep checkbox is checked after checking checkbox for updating corresponding row in Gridview.this my complete source code.Please help Me to keep checkbox inside Gridview checked after update button click.I met scenario that in order to identify which user's data going to be update so.Please help me friends.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID" onpageindexchanging=" grvDetails_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Page">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="radID" runat="server" onclick ="CheckSingleCheckbox(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"/>
<asp:BoundField DataField="FirstName" HeaderText="FirstName"/>
<asp:BoundField DataField="LastName" HeaderText="LastName"/>
<asp:BoundField DataField="Gender" HeaderText="Gender"/>
<asp:BoundField DataField="Email" HeaderText="Email"/>
<asp:BoundField DataField="Phone" HeaderText="Phone"/>
<asp:BoundField DataField="ContactAddres" HeaderText="ContactAddres"/>
<asp:BoundField DataField="State" HeaderText="ContactState"/>
<asp:BoundField DataField="Country" HeaderText="ContactCountry"/>
<asp:BoundField DataField="CommunicationAddress" HeaderText="CommunicationAddress"/>
<asp:BoundField DataField="State1" HeaderText="CommunicationState"/>
<asp:BoundField DataField="Country1" HeaderText="CommunicationCountry"/>
<asp:BoundField DataField="statec" HeaderText="ContactCountry" ShowHeader="false" />
<asp:BoundField DataField="countryc" HeaderText="CommunicationAddress" ShowHeader="false" />
<asp:BoundField DataField="CommunicationState" HeaderText="CommunicationState" ShowHeader="false" />
<asp:BoundField DataField="CommunicationCountry" HeaderText="CommunicationCountry" ShowHeader="false" />
</Columns>
</asp:GridView>
And this is my c# page and I'm posting code for update
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections;
namespace Reg
{
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridView();
populate1();
populate2();
}
}
public void populate1()
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand com = new SqlCommand("select *from CountryDetail", con);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ddlCountryPermanent.DataTextField = ds.Tables[0].Columns["Country"].ToString();
ddlCountryPermanent.DataValueField = ds.Tables[0].Columns["CID"].ToString();
ddlCountryPermanent.DataSource = ds.Tables[0];
ddlCountryPermanent.DataBind();
ddlCountryPermanent.Items.Insert(0, "Select");
ddlCountryCommunication.DataTextField = ds.Tables[0].Columns["Country"].ToString();
ddlCountryCommunication.DataValueField = ds.Tables[0].Columns["CID"].ToString();
ddlCountryCommunication.DataSource = ds.Tables[0];
ddlCountryCommunication.DataBind();
ddlCountryCommunication.Items.Insert(0, "Select");
}
public void populate2()
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand com = new SqlCommand("select *from StatesDetail", con);
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(ds);
ddlStatePermanent.DataTextField = ds.Tables[0].Columns["State"].ToString();
ddlStatePermanent.DataValueField = ds.Tables[0].Columns["SID"].ToString();
ddlStatePermanent.DataSource = ds.Tables[0];
ddlStatePermanent.DataBind();
ddlStatePermanent.Items.Insert(0, "Select");
ddlStateCommunication.DataTextField = ds.Tables[0].Columns["State"].ToString();
ddlStateCommunication.DataValueField = ds.Tables[0].Columns["SID"].ToString();
ddlStateCommunication.DataSource = ds.Tables[0];
ddlStateCommunication.DataBind();
ddlStateCommunication.Items.Insert(0, "Select");
}
protected void saveButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection con;
SqlCommand cmd = new SqlCommand();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
cmd = new SqlCommand("proc_Registers", con);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
if (RdoGender.SelectedItem.Value == "0")
{
cmd.Parameters.AddWithValue("#Gender", "0");
}
else
{
cmd.Parameters.AddWithValue("#Gender", "1");
}
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("#ContactAddres", txtAddressCon.Text);
var statcon = ddlStatePermanent.SelectedItem.Value;
cmd.Parameters.AddWithValue("#ContactState", statcon);
var ddlCourtyCon = ddlCountryPermanent.SelectedItem.Value;
cmd.Parameters.AddWithValue("#ContactCountry", ddlCourtyCon);
cmd.Parameters.AddWithValue("#CommunicationAddress", txtAddressPer.Text);
var statper = ddlStateCommunication.SelectedItem.Value;
cmd.Parameters.AddWithValue("#CommunicationState", statper);
var ddlCourtyPer = ddlCountryCommunication.SelectedItem.Value;
cmd.Parameters.AddWithValue("#CommunicationCountry", ddlCourtyPer);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
gridView();
}
public void gridView()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("proc_FinalDataGridviewNew", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.PageSize = 5;
GridView1.Columns[1].Visible = true;
GridView1.Columns[13].Visible = true;
GridView1.Columns[14].Visible = true;
GridView1.Columns[15].Visible = true;
GridView1.Columns[16].Visible = true;
Page.DataBind();
GridView1.Columns[1].Visible = false;
GridView1.Columns[13].Visible = false;
GridView1.Columns[14].Visible = false;
GridView1.Columns[15].Visible = false;
GridView1.Columns[16].Visible = false;
}
protected void grvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataBind();
gridView();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[13].Visible = false;
e.Row.Cells[14].Visible = false;
e.Row.Cells[15].Visible = false;
e.Row.Cells[16].Visible = false;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("radID") as CheckBox;
if (chk.Checked)
{
var ID = row.Cells[1].Text;
var fname = row.Cells[2].Text;
var lname = row.Cells[3].Text;
var gendr = row.Cells[4].Text;
var mail = row.Cells[5].Text;
var phne = row.Cells[6].Text;
var addrscon = row.Cells[7].Text;
var statecon = row.Cells[13].Text;
var countrycon = row.Cells[14].Text;
var addrsper = row.Cells[10].Text;
var stateper = row.Cells[15].Text;
var countryper = row.Cells[16].Text;
txtID.Text = ID;
txtFirstName.Text = fname;
txtLastName.Text = lname;
string gndr;
if (gendr == "Male")
{
gndr = "0";
}
else
{
gndr = "1";
}
RdoGender.SelectedValue = gndr;
txtEmail.Text = mail;
txtPhone.Text = phne;
txtAddressCon.Text = addrscon;
ddlStatePermanent.SelectedValue = statecon;
ddlCountryPermanent.SelectedValue = countrycon;
txtAddressPer.Text = addrsper;
ddlStateCommunication.SelectedValue = stateper;
ddlCountryCommunication.SelectedValue = countryper;
DataBind();
gridView();
}
else
{
lblMessage.Text = "*Please select any row to Update";
}
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
string id = txtID.Text;
string fname = txtFirstName.Text;
string lname = txtLastName.Text;
string gendr = RdoGender.Text;
string mail = txtEmail.Text;
string phne = txtPhone.Text;
string addrscon = txtAddressCon.Text;
string statecon = ddlStatePermanent.SelectedItem.Value;
string countrycon = ddlCountryPermanent.SelectedItem.Value;
string addrsper = txtAddressCon.Text;
string stateper = ddlStateCommunication.SelectedItem.Value;
string countryper = ddlCountryCommunication.SelectedItem.Value;
SqlConnection con = con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("proc_UpdateRegisters", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#FirstName", fname);
cmd.Parameters.AddWithValue("#LastName", lname);
cmd.Parameters.AddWithValue("#Gender", gendr);
cmd.Parameters.AddWithValue("#Email", mail);
cmd.Parameters.AddWithValue("#Phone", phne);
cmd.Parameters.AddWithValue("#ContactAddres", addrscon);
cmd.Parameters.AddWithValue("#ContactState", statecon);
cmd.Parameters.AddWithValue("#ContactCountry", countrycon);
cmd.Parameters.AddWithValue("#CommunicationAddress", addrsper);
cmd.Parameters.AddWithValue("#CommunicationState", stateper);
cmd.Parameters.AddWithValue("#CommunicationCountry", countryper);
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
con.Close();
gridView();
}
// row delete
protected void btnDelete_Click(object sender, EventArgs e)
{
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].
Cells[0].FindControl("radID");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
DeleteMultipleRecords(idCollection);
GridView1.DataBind();
}
else
{
lblMessage.Text = "*Please select any row to delete";
}
DataBind();
gridView();
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from Registers" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
protected void polyuria2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked == true)
{
var peradrs = txtAddressCon.Text;
var stat = ddlStatePermanent.SelectedIndex;
var contry = ddlCountryPermanent.SelectedIndex;
txtAddressPer.Text = peradrs;
ddlStateCommunication.SelectedIndex = stat;
ddlCountryCommunication.SelectedIndex = contry;
}
}
}
}
This is because the ViewState unable to maintain CheckBox state from GridView column. Easiest solution will be:
Add 'OnCheckedChanged' and 'OnDataBinding' event for checkbox column
<ItemTemplate>
<asp:CheckBox ID="radID" runat="server" OnCheckedChanged="radID_CheckedChanged" OnDataBinding="radID_DataBinding" />
</ItemTemplate>
Next step will be implement these events:
protected void radID_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
if (checkbox.Checked)
{
ViewState[checkbox.UniqueID] = true;
}
else
{
ViewState.Remove(checkbox.UniqueID);
}
}
protected void radID_DataBinding(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
checkbox.Checked = ViewState[checkbox.UniqueID] != null;
}
Please let me know, if this helps.

Categories