where to check the state of dynamically created checkboxes - asp.net

Hello in my programme I need to create dynamically checkboxlist with items - got from teh database.
The problem is when Clicking a button i should get the text from cn only checked checkboxes and I should redirect the user to another page
And I have difficulty with determining width of the controls are checkedore
if I checked immediately after they are added
So if I write
if (mycheckbox.Items[s].Selected==true)
after this line
Page.FindControl("form1").Controls.Add(mycheckbox);
they are not checked still so this will be always false)
On postback event (clicking the button ) - we know on postback event dynamic controls no longer exist)
here is my code
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
s++;
}
}//End of try
catch (Exception ex)
{ }
}//end of for

I've implemented a client-side check using jQuery in my online Quiz engine (demo: http://webinfocentral.com): the extract from that code snippet follows:
var _rows = $(this).find('tr');
for (i = 0; i < _rows.length; i++) {
// find out if checkbox is checked
_checked = $(_rows[i]).find('input:checkbox').is(':checked');
}

conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
mycheckboxList = new CheckBoxList();
mycheckboxList.ID = "chkblextracharge" + i.ToString();
while (rd.Read())
{
ListItem LI = new ListItem(rd["Extra_Charge_Description"].ToString(), s.ToString());
LI.Selected = rd["Selected_Criteria"] == "TRUE";
mycheckboxList.Items.Add(LI);
s++;
}
Page.FindControl("form1").Controls.Add(mycheckboxList);

Related

Changing the parameter in sql query of ASP.NET page - with button_click event, sql query in every button click

I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV

why when unchecking checkbox - checkedChanged event doesn't execute

In my function createCheckboxes() I dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But for example if a client decides to check one checkbox and alue is added to the session, but then he suddenly decides that he want to uncjheck that checbox - so I should delete this value from the arraylist and then from the session.
The big problem is that it seems that when unchecking the Checkedchanged event handler is never executed and this code is never executed
else if (!chk.Checked)
{
lblProba.Text += "You wll be delited";
for (int i = 0; i < element.Count; i++)
{
if (element[i].ToString().Equals(chk.InputAttributes["value"]) == true)
element.Remove(element[i]);
}
}
My full code
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
element.Add(chk.InputAttributes["value"]);
}
else if (!chk.Checked)
{
lblProba.Text += "You wll be delited";
for (int i = 0; i < element.Count; i++)
{
if (element[i].ToString().Equals(chk.InputAttributes["value"]) == true)
element.Remove(element[i]);
}
}
for (int t = 0; t < element.Count; t++)
{
Session["chk"]+= element[t].ToString();
}
}
protected void createCheckboxes()
{
chkddlchange = true;
int numTourists = 2;
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.EnableViewState =true ;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
s++;
}
//myche.Add(mycheckbox.Items[s].Text);
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}
Have you mentioned Autopostback=true while creating your checkbox? If not than please do it and see if it works or not.

remove previously stored value of a checkbox in a session when user unchecks this checkbox

I try to dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But here occurs a big problem for me.
For example a client decides to check one checkboxes and it's value attribute is added to the session, but then he suddenly decides that he doesn't want that checbox to be checked and he unchecks it - it's ok, but this value will stay stored in the session and I don't eant that.
So is there any way to delete this value when the user unchecks the checkbox
protected void btnProba_Click(objectore sender, EventArgs e)
{
lblProba.Text = ((String)Session["chk"]);
// lblProba.Text = pr.ToString();
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
//lblProba.Text += chk.Text;
//myche.Add(chk.Text);
Session["chk"] += chk.InputAttributes["value"];
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
chkddlchange = true;
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
}
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}
It seems like you store checkboxes values as a concatenated string in Session["chk"]. It makes removing anything from there pretty hard. I guess it might be better to store a list of strings in Session["chk"], so you would be able to easy add/remove entries from there...

Dynamically added checkboxs are not working in asp.net using c#?

i am adding multiple checkboxes in my asp.net page by doing this:
public static CheckBox[] chck;
on pageload:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
SqlCommand cmd = new SqlCommand("select count(CompanyName) from Stock_Company");
cmd.Connection = con;
comno = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
chck = new CheckBox[comno];
}
}
now i have a function which is generating the checkboxes :
public void generatecheckbox1()
{
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
chck[i] = new CheckBox();
chck[i].ID = "chck" + Convert.ToString(i);
chck[i].Text = dt.Rows[i]["CompanyName"].ToString();
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
}
}
and i am calling this on a combobox event:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
as far as this all are working fine ... but in a button click i want to get the select checkbox's text which i am not getting
i made a function :
public string getbsecompany()
{
string companyname = "";
string bsetricker = "";
con.Open();
SqlCommand cmd = new SqlCommand("select CompanyName from Stock_Company");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (chck[i].Checked == true) **THE PROBLEM IS HERE**
{
companyname = chck[i].Text;
con.Open();
SqlCommand cmdd = new SqlCommand("select BSETickerCode from Stock_Company where CompanyName='" + companyname + "'");
cmdd.Connection = con;
bsetricker += bsetricker + "+" + cmdd.ExecuteScalar();
con.Close();
}
}
return bsetricker;
}
and i am calling it here:
protected void btnusersave_Click(object sender, EventArgs e)
{
string bsetricker = "";
bsetricker = getbsecompany();
}
the problem is i am not getting the checked box's text. when i am checking if (chck[i].Checked == true) i am gettin false and all checkboxes are checked.
What should i do now?
any help
The dynamic controls should added to page in On_Init() for each time if you want it display in page.
Else there's nothing you can get.
Plus, better not use a static value to contains checkBox List, it will cause problem when multi user access same page. You can save them in session or try this.Form.FindControls()

Dynamic Checkbox event handler asp.net

I found a few questions related to this, but none that I could figure out how to apply to my issue. Anyway, I have a ASP webform that pulls questions and answers from a database and puts them in a table. In the table, I have a column with a checkbox where the user can flag questions. My problem is that event handler for the CheckChanged event is not firing. I read some things about postback and whatnot, but my issue is that these controls are not created until the retrieve question button is pressed. Any help or pointers would be great.
Thanks,
Joseph
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ScienceAssessmentToolASP
{
public partial class createnewtest : System.Web.UI.Page
{
private int n;
private SqlConnection conn = null;
private List<int> flaggedQuestions = new List<int>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
GetConn();
ExecuteRetrieval();
n = 1;
}
catch (Exception ex) { n = 0; Response.Write("for debugging: " + ex); }
finally { if (conn != null) conn.Close(); }
if (n < 0)
//Label1.Text = "Connection Successful";
Label3.Text = "Failed to Connect to Database, please contact the administrator.";
}
private void GetConn()
{
string connString = #"
removed ";
conn = new SqlConnection(connString);
conn.Open();
}
private void ExecuteRetrieval()
{
List<string> names = new List<string>(),
types = new List<string>();
SqlDataReader reader = null;
string query = "select * from [ScienceQA] where [GradeLevel] = " + DropDownList1.Text +
" and [Topic] = '" + DropDownList2.Text + "';";
SqlCommand cmd = new SqlCommand(query, conn);
reader = cmd.ExecuteReader();
TableHeaderRow headerRow = new TableHeaderRow();
TableHeaderCell idH = new TableHeaderCell();
TableHeaderCell questionH = new TableHeaderCell();
TableHeaderCell answerH = new TableHeaderCell();
TableHeaderCell flagH = new TableHeaderCell();
idH.Text = "ID";
questionH.Text = "Question";
answerH.Text = "Answer";
flagH.Text = "Flag";
headerRow.Cells.Add(idH);
headerRow.Cells.Add(questionH);
headerRow.Cells.Add(answerH);
headerRow.Cells.Add(flagH);
resultTable.Controls.Add(headerRow);
while (reader.Read())
{
TableRow row = new TableRow();
TableCell idCell = new TableCell();
TableCell qCell = new TableCell();
TableCell aCell = new TableCell();
TableCell flag = new TableCell();
idCell.Text = reader[0].ToString();
qCell.Text = reader[1].ToString();
aCell.Text = reader[2].ToString();
CheckBox flagBox = new CheckBox();
flagBox.ID = "flag" + idCell.Text.ToString();
//flagBox.Text = "Flag";
flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
flag.Controls.Add(flagBox);
row.Cells.Add(idCell);
row.Cells.Add(qCell);
row.Cells.Add(aCell);
row.Cells.Add(flag);
resultTable.Controls.Add(row);
}
Label4.Visible = true;
flagCounter.Visible = true;
resultTable.Visible = true;
}
protected void flagButton_Click(object sender, EventArgs e)
{
CheckBox lb = (CheckBox)sender;
int questionID = Convert.ToInt32(lb.Text.Substring(4));
if (lb.Checked)
{
lb.Checked = false;
flaggedQuestions.Add(questionID);
flagCounter.Text = Convert.ToString(Convert.ToInt32(flagCounter.Text) - 1);
}
else
{
lb.Checked = true;
flaggedQuestions.Remove(questionID);
flagCounter.Text = Convert.ToString(Convert.ToInt32(flagCounter.Text) + 1);
}
}
}
}
Try setting AutoPostBack to true when you create the control:
flagBox.AutoPostBack = true;
This makes it so the event will cause a postback. If you don't have this the code won't fire until you submit the form.
I figured it out. I guess I didnt need anything in button handler, since the clicking of the button causing a postback. So I put all the button1 handler stuff in my pageload with a if(postback) check and that worked.

Resources