How to keep check box checked after button click for update - c#

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.

Related

How can I get the row selected in my gridview to display in my text boxes?

I have got a Gridview that display's only certain columns from the database table. There is a select button and delete button in my GridView as well.
This is the code for the GridView
<asp:GridView ID="GridViewClient" runat="server" DataKeyNames="FirstName"
OnSelectedIndexChanged="GridViewClient_SelectedIndexChanged"
OnRowDeleting="GridViewClient_RowDeleting">
<Columns>
<asp:CommandField HeaderText="Update" ShowSelectButton="True" />
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
Then when the user selects the select button it should then display the entire table in the text boxes.
This is the code for the select button:
protected void GridViewClient_SelectedIndexChanged(object sender, EventArgs e)
{
EditClient.Visible = true;
GridViewRow row = GridViewClient.SelectedRow;
string constr = #"string";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_newclient"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
txtFirstName.Text = sdr["FirstName"].ToString();
txtLastName.Text = sdr["LastName"].ToString();
txtContactNumber.Text = sdr["ContactNumber"].ToString();
txtEmailAddress.Text = sdr["EmailAddress"].ToString();
txtAddress.Text = sdr["Address"].ToString();
txtRestrictions.Text = sdr["Restrictions"].ToString();
txtThirdPartySupport.Text = sdr["ThirdPartySupport"].ToString();
txtBasicNotes.Text = sdr["BasicNotes"].ToString();
}
con.Close();
}
}
Update.Visible = true;
}
The texboxes are hidden on page load and will only be visible on select
What happens now is that when I click on the select button on any row the first row of the GridView displays in the text box?
I am not sure what I am doing wrong here?
Thanks
I don't fully understand what you are asking as i can't see all your code but i think the issue may be that you are only reading the first row with the data reader. you could try something like this
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
while (sdr.Read())
{
//I'm not sure what you want to do here? i've just addede to the existing text in the textbox
txtFirstName.Text += sdr["FirstName"].ToString();
txtLastName.Text += sdr["LastName"].ToString();
txtContactNumber.Text += sdr["ContactNumber"].ToString();
txtEmailAddress.Text += sdr["EmailAddress"].ToString();
txtAddress.Text += sdr["Address"].ToString();
txtRestrictions.Text += sdr["Restrictions"].ToString();
txtThirdPartySupport.Text += sdr["ThirdPartySupport"].ToString();
txtBasicNotes.Text += sdr["BasicNotes"].ToString();
}
}
}
I guess you have primarykey of table tbl_newclient in your Gridview. Then on select take the primary key from gridview and append a where condition on your sql query then it should return the desired data.
protected void GridViewClient_SelectedIndexChanged(object sender, EventArgs e)
{
EditClient.Visible = true;
var primarykey = GridViewClient.SelectedRow.Cells[0].Text; // 0 cell index primary key
string constr = #"string";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_newclient where yourprimarykey=#primarykey"))
{
cmd.Parameters.AddWithValue("#primarykey", primarykey);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
while (sdr.Read())
{
txtFirstName.Text = sdr["FirstName"].ToString();
txtLastName.Text = sdr["LastName"].ToString();
txtContactNumber.Text = sdr["ContactNumber"].ToString();
txtEmailAddress.Text = sdr["EmailAddress"].ToString();
txtAddress.Text = sdr["Address"].ToString();
txtRestrictions.Text = sdr["Restrictions"].ToString();
txtThirdPartySupport.Text = sdr["ThirdPartySupport"].ToString();
txtBasicNotes.Text = sdr["BasicNotes"].ToString();
}
}
}
con.Close();
}
}
Update.Visible = true;
}

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);
}

Asp.Net finding in Code-behind edited values in GridView with autogenerated columns

I am trying to create a user control of a gridview that will be able to display, edit and delete records, being bound to any datatable.
In my user control I have:
<asp:GridView ID="EditableGrid" runat="server" Width="500px" Height="500px" AllowSorting="True"
AutoGenerateColumns = "true"
AutoGenerateDeleteButton ="true" AutoGenerateEditButton="true"
OnRowEditing="EditableGrid_RowEditing"
OnRowCancelingEdit="EditableGrid_RowCancelingEdit"
OnRowUpdating="EditableGrid_RowUpdating"
OnRowDeleting="EditableGrid_RowDeleting"
></asp:GridView>
In my code behind I have:
public void InitGrid(string theconnstr, string thetablename)
{
connstr = theconnstr;
tablename = thetablename;
// Session["edgconnstr"] = connstr;
// Session["edgtablename"] = tablename;
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (!rd.HasRows) return;
fields = new List<EdField>();
for (int i =0; i < rd.FieldCount; i++)
{
fields.Add(new EdField(rd.GetName(i), rd.GetDataTypeName(i)));
}
}
}
con.Close();
}
public void Bind()
{
// connstr = (String)Session["edgconnstr"];
// tablename = (String)Session["edgtablename"];
con = new SqlConnection(connstr);
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM " + tablename;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
EditableGrid.DataSource = dt;
EditableGrid.DataBind();
EditableGrid.Visible = true;
}
}
}
con.Close();
}
protected void EditableGrid_RowEditing(object sender, GridViewEditEventArgs e)
{
EditableGrid.EditIndex = e.NewEditIndex;
Bind();
}
protected void EditableGrid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
EditableGrid.EditIndex = -1;
Bind();
}
protected void EditableGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
Now I have tried with no success to find the new values of the edited row in the EditableGrid_RowUpdating event handler. I just do not have access to the textboxes, and therefore I cannot run the query to update the old values to the new value. Is what I want to achieve even possible?
Use the e.NewValues Collection.
protected void EditableGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int tx = Convert.ToInt32(e.NewValues[0]);
}

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.

Radio button list selected value not persistent in asp.net

I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}
it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks

Categories