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);
}
Related
Here i have textbox.Similarly, i have table tblpstatus which have two field id and Pstatus.Now what i am trying do is, if the Field Pstatus have text V then textbox must be visible else not. Now the problem is that even if the field Pstatus have text V textbox are not visible.Below is what i have:
Table tructure
id | Pstatus
1 | V
Html
<asp:TextBox ID="TextBox1" runat="server" placeholder="test" ></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button"/><br>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = c.getpstatus();
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Pstatus"].ToString() == "V")
{
Button1.Visible = true;
TextBox1.Visible = true;
}
else
{
Button1.Visible = false;
TextBox1.Visible = false;
}
}
}
Method used
public DataTable getpstatus()
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
string sql = "select * from tblpstatus";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
try this,
if (dt.Rows[0]["Pstatus"].ToString().equals("V"))
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.
I'm trying to build a simple page that will allow for bulk SQL Searches using a text area. The textbox is split on each new line and each line taken as a parameter to query. The resulting row is then added to a DataTable.
There isn't a problem with the query and the DataTable is built and returned as I expected when checked through debug mode. The only problem is when I attempt to bind the DataTable to the gridview , the gridview is left without rows.
I have been scratching my head at this for a hwile now and cannot figure out why the DataTable will not bind. The column names all match up but the actual table in result is unnamed. Is this an issue?
Here's the code.
ASPX:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="SIM NUMBER" HeaderText="SIM NUMBER" />
<asp:BoundField DataField="Voice" HeaderText="Voice" />
<asp:BoundField DataField="IMSI" HeaderText="IMSI" />
<asp:BoundField DataField="Tariff" HeaderText="Tariff" />
<asp:BoundField DataField="Contract Start" HeaderText="Contract Start" />
<asp:BoundField DataField="Supplier" HeaderText="Supplier" />
</Columns>
</asp:GridView>
And the C# Code:
public partial class Query : System.Web.UI.Page
{
protected static string numbers = "";
protected static string number;
protected static DataTable result = new DataTable();
protected static string simNumber;
protected static string voice;
protected static string IMSI;
protected static string tariff;
protected static string contractStart;
protected static string supplier;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
result.Reset();
result.Columns.Add("SIM NUMBER", typeof(string));
result.Columns.Add("Voice", typeof(string));
result.Columns.Add("IMSI", typeof(string));
result.Columns.Add("Tariff", typeof(string));
result.Columns.Add("Contract Start", typeof(string));
result.Columns.Add("Supplier", typeof(string));
numbers = TextArea1.Value.ToString();
search();
GridView1.DataSource = result;
GridView1.DataBind();
}
protected static void search()
{
string[] split = numbers.Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (string line in split)
{
if (line == string.Empty)
continue;
number = line;
getSupplierInfo();
}
}
protected static void getSupplierInfo()
{
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
foreach (DataRow dr in DT.Rows)
{
simNumber = dr["SIM_NUMBER"].ToString();
voice = dr["Voice"].ToString();
IMSI = dr["IMSI"].ToString();
tariff = dr["Tariff"].ToString();
contractStart = dr["Contract_start"].ToString();
supplier = dr["Supplier"].ToString();
addRow();
}
}
protected static void addRow()
{
DataRow simResult = result.NewRow();
simResult["SIM Number"] = simNumber;
simResult["Voice"] = voice;
simResult["IMSI"] = IMSI;
simResult["Tariff"] = tariff;
simResult["Contract Start"] = contractStart;
simResult["Supplier"] = supplier;
result.Rows.Add(simResult);
}
}
Any help would be very much appreciated. I'm sure its something really simple that i'm missing.
Thanks
Try changing:
AutoGenerateColumns="false"
to:
AutoGenerateColumns="true"
I Think you can try like this in aspx file
<Columns>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Your_Field_Name") %>'></asp:Label>
</ItemTemplate>
</Columns>
and in cs file just fit below code
DataTable DT = new DataTable();
using (SqlConnection conn = new SqlConnection(connections.supplierInfo()))
{
string sql = " SELECT * FROM UnionSuppliers WHERE SIM_NUMBER LIKE #parameter ";
conn.Open();
using (SqlCommand select = new SqlCommand
{
CommandType = CommandType.Text,
CommandTimeout = 300,
CommandText = sql,
Connection = conn
})
{
select.Parameters.AddWithValue("#parameter", number);
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter.SelectCommand = select;
adapter.Fill(ds);
DT = ds.Tables[0];
}
}
And now bind your Datatable to Grid View.
GridView1.DataSource = DT;
GridView1.DataBind();
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.
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