Dynamic Checkbox event handler asp.net - 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.

Related

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

Dynamically adding Table rows

I am trying to add values in table rows on button click. It's working on database but not working on web page. It override on last row on page.
How can I generate new row on every button click.
here is my button click code--
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//Label2.Visible = false;
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
CheckBox cb1 = new CheckBox();
I = Hidden1.Value;
I += 1;
cb1.ID = "cb1" + I;
TableRow Table1Row = new TableRow();
Table1Row.ID = "Table1Row" + I;
TableCell RCell1 = new TableCell();
RCell1.Controls.Add(cb1);
TableCell RCell2 = new TableCell();
RCell2.Text = txtName.Text;
tblLanguagesRow.Cells.Add(RCell1);
tblLanguagesRow.Cells.Add(RCell2);
tblLanguages.Rows.Add(tblLanguagesRow);
Hidden1.Value = I;
btnAdd.Visible = true;
btnDelete.Visible = true;
Label2.Visible = true;
Label2.Text = "Successfully Added";
add();
}
txtName.Text = "";
}
public int add()
{
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("hrm_AddLanguages", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Name", SqlDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
command.Parameters.Add("#CreatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#UpdatedBy", SqlDbType.BigInt).Value = 1;
command.Parameters.Add("#IsDeleted", SqlDbType.Bit).Value = 0;
sqlConnection.Open();
return command.ExecuteNonQuery();
}
Please Help me.
If possible try to do this using Grid view. It is better to use grid view instead of table.
Check out below link. It will help you to find your solution.
DataTable in ASP.Net Session

Gridview does not show SQL Server database records

I'm designing a web system for my fyp.
I use SqlDependency to get table change info from cache.
I used SqlDataAdapter, dataSet and gridview, but it doesn't show any result on screen.
Can you tell me where the problem is in my code?
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] == null)
{
gvshipOrders.DataSource = Cache["shipOrders"];
gvshipOrders.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
gvshipOrders.DataSource = ds;
gvshipOrders.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
I've found the problem,
public partial class OrderProccessing : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] == null)
{
Response.Redirect("Default.aspx");
}
else
{
string value = Session["email"].ToString();
Classes.AddAddress addcuid = new Classes.AddAddress(value);
txtstaffname.Text = addcuid.addStaffName().ToString();
txtstaffID.Text = addcuid.fetchStaffID().ToString();
}
}
protected void refresh_Click(object sender, EventArgs e)
{
if (Cache["shipOrders"] != null)
{
myGrid.DataSource = Cache["ShipOrders"];
myGrid.DataBind();
lblOrderNotification.Text = "last order recived at " + DateTime.Now.ToString();
}
else
{
string xconnectionString = ConfigurationManager.ConnectionStrings["LGDB"].ToString();
SqlConnection sqlCon = new SqlConnection(xconnectionString);
SqlDataAdapter da = new SqlDataAdapter("viewOrders", sqlCon);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
da.Fill(ds);
SqlCacheDependency XsqlcacheDependecy = new SqlCacheDependency("secaloTest1", "customerShipOrder");
//caching shipOrders table data
/*
Cache.Insert("shipOrders", ds, null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
another overloaded method is used */
Cache.Insert("shipOrders", ds, XsqlcacheDependecy);
myGrid.DataSource = ds;
myGrid.DataBind();
lblOrderNotification.Text = "orders retrived from database at " + DateTime.Now.ToString();
}
}
}

where to check the state of dynamically created checkboxes

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

How to populate the date present in the database table to Calender asp.net?

My table in the database has the following columns id , eventstart , eventend , eventname
I am trying to bind the event name plus the event start date in the cell of the calender on the date which it is occurring
However i am not able to do so
Following is my code snippet
protected void myCal_DayRender1(object sender, DayRenderEventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter cmd = new SqlDataAdapter("Select * FROM event", con);
cmd.Fill(ds, "Table");
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["eventstart"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["eventstart"];
if (dtEvent.Equals(e.Day.Date))
{
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.Width = 100;
lbl.Height = 100;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = TextBoxName.Text + "" + TextBoxStart.Text + "" + TextBoxEnd.Text;
e.Cell.Controls.Add(lbl);
}
}
}
}
else
{
}
}
Please help someone
Ok, once again from the start. Now I think I got it. Your problem is probably caused by comparing date with time to date. To get only date without time You can use dt.Date as You can see below. You can consider loading all data on page load because of performance reasons.
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
//get data
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand =
new SqlCommand("select * from event", connection);
adapter.Fill(ds);
}
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
//mark dates in calendar
foreach (DataRow dr in ds.Tables[0].Rows)
{
DateTime dt = (DateTime)dr.Field<DateTime?>("eventstart");
if (e.Day.Date == dt.Date)
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
//add event lable to day
Label lbl = new Label();
lbl.BorderColor = System.Drawing.Color.Black;
lbl.BorderStyle = BorderStyle.Double;
lbl.BackColor = System.Drawing.Color.BlanchedAlmond;
lbl.Text = "Event text";
e.Cell.Controls.Add(lbl);
}
}
}

Resources