I am having an issue with some of my dynamic checkboxes on a project I am working on.
I have a tables, and in one cell per row, I have a checkbox. This checkbox is checked to "flag" that record. The records in the table are populated on a button click, after the user has set a series of filters. Therefore, the table contents completely change on each postback.
I use a list to preserve which records were already flagged, so that if a record appears that was previously checked, it will be checked on that retrieval too.
I am performing this check against my list in my page_load function and I can see through debugging that it is getting set correctly. However, when the page is done loading, the checked status is often wrong.
Do I need to move my checkbox state verification step to another part of the page lifecycle?
Any tips would be great. I found some questions on asp.net issues with checkboxes, but I they did not seem to be relevant to my issue.
Here is the code, feel free to critique any/all of it :)
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)
{
if (IsPostBack)
{
var temp = (List<int>)Session["flaggedQuestions"];
if (temp != null)
flaggedQuestions = temp; ;//retrieve flags from session
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.";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
private void GetConn()
{
string connString = #"laalalala";
conn = new SqlConnection(connString);
conn.Open();
}
private void ExecuteRetrieval()
{
SqlDataReader reader = null;
string query;
if (!IsPostBack)
{
query = "select * from [ScienceQA]";
flaggedQuestions = (List<int>)Session["flaggedQuestions"];//retrieve flags from session
}
else 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();
int id = Convert.ToInt32(idCell.Text);
flagBox.AutoPostBack = true;
flagBox.CheckedChanged += new System.EventHandler(flagButton_Click);
flagBox.EnableViewState = true;
flagBox.ViewStateMode = ViewStateMode.Enabled;
if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
flagBox.Checked = true;
else flagBox.Checked = false;
flagBox.Text = id.ToString();
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.ID.Substring(4));
if (lb.Checked && !flaggedQuestions.Contains(questionID))
{
//lb.Checked = false;
flaggedQuestions.Add(questionID);
flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
}
else
{
//lb.Checked = true;
flaggedQuestions.Remove(questionID);
flagCounter.Text = Convert.ToString(flaggedQuestions.Count);
}
Session["flaggedQuestions"] = flaggedQuestions;//store questions to session
}
protected void createTestButton_Click(object sender, EventArgs e)
{
//create a test
bool sendQuery = true;
string author = Session["user"].ToString();
string accessLevel = accessDropdown.Text;
int gradeLevel = Convert.ToInt32(DropDownList1.Text);
int questionCount = flaggedQuestions.Count();
string testType = testTypeDropDown.Text;
string description = descriptionBox.Text;
string questionString = "";
for (int i = 0; i < flaggedQuestions.Count(); i++)
questionString += flaggedQuestions[i] + ",";
string query = #"Insert into Tests Values ('" + author + "','" + questionString
+ "','" + accessLevel + "','" + gradeLevel + "','" + questionCount + "','"
+ testType + "','" + description +"');";
//check parameters
if (accessLevel == "")
{
errorLabel.Text = "Please choose an access level.";
sendQuery = false;
}
if (questionCount == 0)
{
errorLabel.Text = "Please flag a set of questions before creating a test.";
sendQuery = false;
}
if (testType == "")
{
errorLabel.Text = "Please choose a test type";
sendQuery = false;
}
if (description == "")
{
errorLabel.Text = "Please describe your test";
sendQuery = false;
}
if (sendQuery)
{
try
{
GetConn();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Prepare();
int n;
n = cmd.ExecuteNonQuery();
}
catch (Exception e2) { n = 0; }
if (n == 1)
errorLabel.Text = "Test Created Successfully";
else errorLabel.Text = "Test Creation Failed, please check your parameters.";
}
}
}
}
Here was the solution that worked for me, moving the checkbox state check to the onprerender function.
protected override void OnPreRender(EventArgs e)
{
foreach (TableRow row in resultTable.Rows)
{
var cell = row.Cells[3];
foreach (Control control in cell.Controls)
{
var flagBox = control as CheckBox;
if (flagBox != null)
{
int id = Convert.ToInt32(flagBox.ID.Substring(4));
if (flaggedQuestions.Contains(id) && flagBox.ID == "flag" + id)
flagBox.Checked = true;
else flagBox.Checked = false;
}
}
}
}
You probably need to update the checked state of the checkboxes in PreRender as that occurs after the button click event has fired.
Related
I'm creating a restaurant ordering system and cant figure out how to send the completed order back into the access database and across to the kitchen view form. It creates buttons for the user to choose which items they want from the database. I need it to get the highest orderID from the listview where the order is and loop through each item getting the MenuID, time and tableno from the till view. Can answer any questions as may not have explained it clearly. Here is some of the code for the till view form. Any help would be appreciated.
public TillView()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int i = 0;
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
string sqlStr;
dbConnector.Connect();
sqlStr = "SELECT description, CatID FROM tblCategory";
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
Button btn = new Button();
btn.BackColor = Color.Lime;
btn.ForeColor = Color.Black;
btn.Font = new Font(btn.Font.Name, 12, FontStyle.Bold);
btn.Size = new Size(110, 100);
btn.Visible = true;
btn.Tag = dr[1].ToString();
btn.Text = dr[0].ToString();
btn.Name = "btn_ " + i;
i++;
btn.Click += Btn_Click;
flpCategory.Controls.Add(btn);
}
dbConnector.Close();
string time = DateTime.Now.ToString("t");
lblTime.Text = ($"{""}" + time);
lblDate.Text = (DateTime.Now.ToString("dd/MM/yyyy"));
lblServer.Text = Login.server;
}
private void Btn_Click(object sender, EventArgs e)
{
flpItem.Controls.Clear();
int i = 0;
int catID = Convert.ToInt32((sender as Button).Tag.ToString());
clsDBConnector dbConnector = new clsDBConnector();
OleDbDataReader dr;
string sqlStr;
dbConnector.Connect();
sqlStr = "SELECT description, CatID, menuID, cost FROM tblMenu where catid = " + catID;
dr = dbConnector.DoSQL(sqlStr);
while (dr.Read())
{
string Description = Convert.ToString((sender as Button).Tag);
int MenuID = Convert.ToInt32((sender as Button).Tag.ToString());
int Cost = Convert.ToInt32((sender as Button).Tag.ToString());
Button bttn = new Button();
bttn.BackColor = Color.LightSkyBlue;
bttn.ForeColor = Color.Black;
bttn.Size = new Size(105, 95);
bttn.Visible = true;
bttn.Tag = dr[2].ToString() + "-" + dr[3].ToString() ;
bttn.Text = dr[0].ToString();
bttn.Name = "bttn_ " + i;
i++;
bttn.Click += bttn_Click;
flpItem.Controls.Add(bttn);
}
dbConnector.Close();
}
private void bttn_Click(object sender, EventArgs e)
{
string theTag = (sender as Button).Tag.ToString() ;
string[] theTagArray = theTag.Split('-');
int MenuID = Convert.ToInt32(theTagArray[0]);
double cost = Convert.ToDouble(theTagArray[1]);
//lstVOrder.Items.Add(MenuID.ToString());
string Description = Convert.ToString(((sender as Button).Text));
lstVOrder.Font = new Font(Font.Name, 12);
lstVOrder.Items.Add(Description.ToString());
lstVOrder.Items[lstVOrder.Items.Count - 1].SubItems.Add(cost.ToString("N2"));
lstVOrder.Items[lstVOrder.Items.Count - 1].SubItems.Add("");
lstVOrder.Items[lstVOrder.Items.Count - 1].SubItems.Add(MenuID.ToString());
}
I am able to retain the DropDownListCheckbox multi-selected items text inside a label with a button click. I need to search from the database based on the DropDownListCheckBox multi selected items and its related data from a SQL-Server database.
How to achieve the search option using a button click by passing the input from DDL_CB list items or label text to parameterized SQL query?
My requirement: the search feature must display the data in JQgrid based on the text contained in the Label or DDL_CheckBox multi-selected items.
My C# code:
static string value1;
static string value2;
static string value3;
protected void createmaincontrols()
{
//Create a Dynamic Panel
DynamicPanel = new Panel();
DynamicPanel.ID = "DynamicPanel";
DynamicPanel.Width = 1600;
//Create Main Table
var dynamic_filter_table = new WebForms.Table();
dynamic_filter_table.ID = "dynamic_filter_table_id";
TableRow campaign_table_row = new TableRow();
campaign_table_row.ID = "country_table_row";
TableRow campaign_label_row = new TableRow();
campaign_label_row.ID = "country_label_row";
TableCell campaignnamecell = new TableCell();
campaignnamecell.ID = "countrynamecell";
TableCell btncell = new TableCell();
btncell.ID = "btncell";
TableCell labelcell = new TableCell();
labelcell.ID = "labelcell";
//Create Campaigns DDL
DropDownCheckBoxes DDL_checkbox = new DropDownCheckBoxes();
DDL_checkbox.ID = "MainDDL_Countries";
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.ForeColor = System.Drawing.Color.MidnightBlue;
DDL_checkbox.Font.Size = FontUnit.Point(8);
DDL_checkbox.Font.Bold = true;
DDL_checkbox.Font.Name = "Arial";
DDL_checkbox.AddJQueryReference = true;
DDL_checkbox.UseButtons = true;
DDL_checkbox.UseSelectAllNode = true;
DDL_checkbox.Style.SelectBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxWidth = 200;
DDL_checkbox.Style.DropDownBoxBoxHeight = 130;
DDL_checkbox.Texts.SelectBoxCaption = "Select Countries";
DDL_checkbox.Items.Add(new ListItem("SINGAPORE"));
DDL_checkbox.Items.Add(new ListItem("UNITED KINGDOM"));
DDL_checkbox.Items.Add(new ListItem("MALAYSIA"));
DDL_checkbox.Items.Add(new ListItem("INDIA"));
DDL_checkbox.Items.Add(new ListItem("FRANCE"));
DDL_checkbox.Items.Add(new ListItem("GERMANY"));
DDL_checkbox.Items.Add(new ListItem("NORWAY"));
DDL_checkbox.DataTextField = "Country Name";
DDL_checkbox.DataBind();
DDL_checkbox.AutoPostBack = true;
DDL_checkbox.EnableViewState = false;
Button submitbutton = new Button();
submitbutton.ID = "mybutton";
submitbutton.Text = "SubmitSelectedCountries";
submitbutton.Click += new EventHandler(Buttonnew_Click);
submitbutton.Font.Name = "Arial";
submitbutton.Font.Bold = true;
submitbutton.Font.Size = FontUnit.Point(8);
submitbutton.ForeColor = System.Drawing.Color.MidnightBlue;
submitbutton.BackColor = System.Drawing.Color.LightGray;
submitbutton.UseSubmitBehavior = false;
Label lblCampaignName = new Label();
lblCampaignName.ID = "Countries";
lblCampaignName.Font.Bold = true;
lblCampaignName.Font.Size = FontUnit.Point(8);
lblCampaignName.ForeColor = System.Drawing.Color.MidnightBlue;
lblCampaignName.BackColor = System.Drawing.Color.LightGray;
campaignnamecell.Controls.Add(DDL_checkbox);
campaignnamecell.Controls.Add(submitbutton);
campaignnamecell.Controls.Add(lblcountryname);
campaign_table_row.Controls.Add(countrycell);
dynamic_filter_table.Controls.Add(country_table_row);
DynamicPanel.Controls.Add(dynamic_filter_table);
SelectPanel.Controls.Add(DynamicPanel);
}
C# code to retrieve the dropdown checked items in a label using a button click
protected void Buttonnew_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
DropDownCheckBoxes DDL_checkbox = maintable.FindControl("MainDDL_Contries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Country") as Label;
List<String> Country_List = new List<string>();
foreach (System.Web.UI.WebControls.ListItem item in DDL_checkbox.Items)
{
if (item.Selected)
{
Country_List.Add(item.Text);
}
lblcountryname .Text = String.Join(",", Country_List.ToArray());
}
}
How to search the country details based on a parameterized SQL query input from label or dropdowncheckbox selected items?
protected void Button4_Click(object sender, EventArgs e)
{
Table maintable = Select.FindControl("dynamic_filter_table_id") as Table;
int rc = maintable.Rows.Count;
if (rc == 2)
{
//Three country selected in DDL_checkbox
DropDownCheckBoxes d4 = maintable.FindControl("MainDDL_Countries") as DropDownCheckBoxes;
Label lblcountryname = maintable.FindControl("Countries") as Label;
var countryname= test.ToString().Split(new[] { ',', '\n' }).ToArray();
if(countryname.Count() >=1 && countryname.Count() <=3)
{
value1 = countryname.ElementAt(0).ToString();
value2 = countryname.ElementAt(1).ToString();
value3 = countryname.ElementAt(2).ToString();
}
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT C.Country_Name,C.Address FROM COUNTRYTABLE as C WHERE C.Country_Name in(#t4,#t5,#t6)";
cmd.Parameters.Add("#t4", SqlDbType.VarChar).Value = value1;
cmd.Parameters.Add("#t5", SqlDbType.VarChar).Value = value2;
cmd.Parameters.Add("#t6", SqlDbType.VarChar).Value = value3;
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter sql = new SqlDataAdapter(cmd);
DataSet data = new DataSet();
sql.Fill(data);
con.Close();
Session["DataforSearch_DDL"] = data.Tables[0];
}
}
This is admittedly a partial answer. It will get you started.
When you submit a form with multi-selected items, the selected items are passed as comma separated values. Something like this:
value1,value2,etc
You want your query to have a where clause like this:
where someTextfield in ('value1','value2','etc')
or without the quotes for numeric fields. However, you wisely said that you wanted to use parameters.
Here endeth the partial answer.
long-long time ago, I used to do it this way:
for (int i = 0; i < param.Length; i++)
if (param[i] != "" && param[i] != null)
s_comm.Parameters.AddWithValue(tParam + i.ToString(), param[i]);
where:
private string tParam = "#Param";
string[] paramName // Name of the parameters
string[] param // Values for those parameters.
and I was building a statement like this:
string where = "";
if (paramName != null)
for (int i = 0; i < paramName.Length; i++)
if (paramName[i] != "" && paramName[i] != null)
if (i == 0)
where = " WHERE " + paramName[i] + " = " + tParam + i.ToString();
else
where += ", " + paramName[i] + " = " + tParam + i.ToString();
else throw new Exception(noColumnName + " at position #:" + i.ToString());
else where = "";
if (table != "") return "SELECT * FROM " + table + where;
I am sure there are more elegant solutions, but this is a start, right?
Problem with populate specific dropdownlist values from database, i want to shows user all the current data from database tables to let them able to make changes, but i coulnd't shows the specific dropdownlist that user selected before. Im using linqdatasource to show all the dropdownlist value.
public partial class Update : System.Web.UI.Page
{
string cs = Global.CS;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) // only during initial load
{
string id = Request.QueryString["Item_ID"] ?? "";
string sql = "Select * FROM MenuItem WHERE Item_ID = #id";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Id", id);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
if ((string)dr["Category"] == "Breakfast" || (string)dr["Category"] == "Lunch" || (string)dr["Category"] == "Dinner")
{
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
//foreach (var checking in db.Sets)
//{
// string setID = checking.Set_ID.ToString();
// if (setID == (string)dr["Item_ID"])
// {
// ddlAlacarte.DataSourceID = "ldsAlacarte";
// **ddlAlacarte.DataTextField = (string)dr["ItemDesc"].ToString();
// ddlAlacarte.DataValueField = (string)dr["Item_ID"].ToString();**
// }
//}
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
lblId.Text = (string)dr["Item_ID"].ToString();
txtItemName.Text = (string)dr["ItemDesc"];
txtPrice.Text = (string)dr["Price"].ToString();
ddlCategory.Text = (string)dr["Category"];
}
}
else
{
Response.Redirect("MenuAdmin.aspx");
}
DataBind();
dr.Close();
con.Close();
}
}
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCategory.SelectedItem.Text == "Breakfast" || ddlCategory.SelectedItem.Text == "Lunch" || ddlCategory.SelectedItem.Text == "Dinner")
{
ddlAlacarte.Enabled = true;
ddlBeverage.Enabled = true;
ddlSide.Enabled = true;
DataBind();
}
else
{
ddlAlacarte.Enabled = false;
ddlBeverage.Enabled = false;
ddlSide.Enabled = false;
DataBind();
}
}
}
You need to add items in Dropdownlist while reading values.
Add the following code while you are reading values by using SqlDataReader.
while(dr.Read())
{
ListItem listItem = new ListItem();
listItem.Text = dr["Category"].ToString();
listItem.Value = dr["Category"].ToString();
categoryDropDownList.Items.Add(listItem);
}
I would use something like this
dropDownList.Items.Add(
new ListItem(){ Text = dr["Breakfast"], Value = dr["Breakfast"] }
);
and iterate through, populating the dropdown list. Is that what you want ?
Here is my current code behind for the OnRowUpdating event and SQL statement to update the database. It is throwing an exception:
System.NullReferenceException: Object reference not set to an instance of an object.error
Code:
protected void GV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtSu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox1"); // each textbox refers to the Am then Pm day
TextBox txtSu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox2");// sun pm
TextBox txtMo = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox3");// mon am
TextBox txtMo1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox4");//mon pm
TextBox txtTu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox5");
TextBox txtTu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox6");
TextBox txtWe = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox7");
TextBox txtWe1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox8");
TextBox txtTh = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox9");
TextBox txtTh1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox10");
TextBox txtFr = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox11");
TextBox txtFr1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox12");
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
TextBox txtSa1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox14");
string sql = "UPDATE tblEMPLOYEE SET EmployeeID=#ID, " +
"AvailSun=#AvSu, " +
"AvailSun1=#AvSu1, " +
"AvailMon=#AvMo, " +
"AvailMon1=#AvMo1, " +
"AvailTues=#AvTu, " +
"AvailTues1=#AvTu1, " +
"AvailWedn=#AvWe, " +
"AvailWedn1=#AvWe1, " +
"AvailThurs=#AvTh, " +
"AvailThurs1=#AvTh1, " +
"AvailFri=#AvFr, " +
"AvailFri1=#AvFr1, " +
"AvailSat=#AvSa, " +
"AvailSat1=#AvSa1 " +
"WHERE EmployeeID=#ID";
CMethods.executeNonQuery(sql, "#ID", txtID.Text, "#AvSu", txtSu.Text, "#AvSu1", txtSu1.Text, "#AvMo", txtMo.Text, "#AvMo1", txtMo1.Text, "#AvTu", txtTu.Text, "#AvTu1", txtTu1.Text, "#AvWe", txtWe.Text, "#AvWe1", txtWe1.Text, "#AvTh", txtTh.Text, "#AvTh1", txtTh1.Text, "#AvFr", txtFr.Text, "#AvFr1", txtFr1.Text, "#AvSa", txtSa.Text, "#AvSa1", txtSa1.Text, "#ID", ID);
GV.EditIndex = -1;
fillUsers();
}
private void fillUsers()
{
GV.DataSource = CMethods.returnTable("SELECT * FROM tblEMPLOYEE WHERE EmployeeID=" + lblEmployee.Text);
GV.DataBind();
}
In Cmethods
public static class CMethods
{
public static DataTable returnTable(String CommandText, params Object[] values)
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "tbl");
return ds.Tables["tbl"];
}
public static bool executeNonQuery(String CommandText, params Object[] values)
{
bool bln = true;
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
bln = false;
}
finally
{
con.Close();
}
return bln;
}
public static double returnValue(string str)
{
double dblTemp = 0.0D;
string strTemp = String.Empty;
bool blnFirstDec = false;
bool blnFirstNeg = false;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "-")
{
blnFirstNeg = true;
}
if (IsNumeric(str.Substring(i, 1)) || str.Substring(i, 1) == ".")
{
if (str.Substring(i, 1) == ".")
{
if (!blnFirstDec)
{
blnFirstDec = true;
strTemp += ".";
}
}
else
{
strTemp += str.Substring(i, 1);
}
}
}
FindControl control may not return control if you not provide correct control id
for example you have given txtBo13(missing x) but actually you may have txtBox13,
so below code return null for txtSa
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBo13");
when you call Text property of txtSa you will get NullReferenceException
if you have given id as txtBox13, change the code accordingly
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
And also you may have forgot to set #student parameter value
I found strange is that when I check some of the checkbox (generated HTML code), the sub function did not alert (or display message) which checkbox is being checked.
Am I missing something?
Inside the WebForm.aspx
<script type="text/javascript">
function sub()
{
for (i=0; i<arrChecks.length; i++)
{
var attribute = arrChecks[i].getAttribute("xid")
if (attribute == elementName)
{
// if the current state is checked, unchecked and vice-versa
if (arrChecks[i].checked)
{
arrChecks[i].checked = false;
} else {
arrChecks[i].checked = true;
alert("Checked!");
}
} else {
arrChecks[i].checked = false;
}
}
}
</script>
Inside the WebForm.cs
protected void ButtonCheckDate_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB("Data Source=JACKSERVERA;Initial Catalog=tablea;User Id=tableuser;Password=tablepassword");
if ((TextBox2.Text != null) && (TextBox2.Text != ""))
{
try
{
String res = "";
SqlCommand command = conn.CreateCommand();
SqlDataReader reader;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * from overviewtable where [dated] = #PDATED";
command.Parameters.AddWithValue("#PDATED", TextBox2.Text);
command.Connection = conn;
sqlstmt.Text = command.CommandText;
conn.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
res = res + "<form name=\"input\" runat=\"server\"><table border=1>";
while (reader.Read())
{
res = res + "<tr>";
string thetime = (string)reader["time"];
string thevenue = (string)reader["venue"];
int numfreeseat = (int)reader["freeseat"];
int occupiedseat = 0;
SqlCommand bkcommand = conn.CreateCommand();
SqlDataReader bookinglist;
bkcommand.CommandType = System.Data.CommandType.Text;
bkcommand.CommandText = "SELECT count(*) from venuea where [dated] = #PDATED";
bkcommand.Parameters.AddWithValue("#PTIME", thetime);
bkcommand.Connection = conn;
sqlstmt.Text = bkcommand.CommandText;
bookinglist = bkcommand.ExecuteReader();
while (bookinglist.Read())
{
if (bookinglist.HasRows)
{
occupiedseat = (int)bookinglist.GetValue(0);
}
}
int leftnumofseat = numfreeseat - occupiedseat;
string color = "";
Boolean fullyoccupied = false;
if (leftnumofseat > 0)
{
if (leftnumofseat == numfreeseat)
{
// white
color = "#FFFFFF";
}
else
{
// light gray - partial occupied
color = "#B8B8B8";
}
}
else
{
// dark gray - fully occupied
color = "#505050";
fullyoccupied = true;
}
res = res + "<td bgcolor=\"" + color + "\">";
res = res + "Available: " + leftnumofseat + "/" + numfreeseat + "";
res = res + "</td>";
string checkboxval = TextBox2.Text + "_" + thetime + "_" + thevenue;
res = res + "<td>";
if (fullyoccupied == false)
{
res = res + "<input type=\"checkbox\" name=\"xid\" value=\"" + checkboxval + "\" runat=\"server\" />";
}
else
{
res = res + "FULL";
}
res = res + "</td>";
res = res + "</tr>";
}
res = res + "</table><input type=\"submit\" value=\"Submit\" OnClick=\"sub\" runat=\"server\"></form>";
}
LabelDateSelection.Text = res;
conn.Close();
}
catch (Exception err)
{
errormsg.Text = err.Message;
}
}
else
{
LabelDateSelection.Text = "Enter Date!";
}
}
Take out this part from you code & see if it works runat=\"server\"
i am not sure if you can create and ASP.net server control as you are trying too & you are sending output to the client while runat=\"server\" is rendered by the server . check you HTML code & see how it looks.
Create HTML control dynamically or create simple HTML control if that can work with your case.
look at the example how to pragmatically create controls
http://msdn.microsoft.com/en-us/library/kyt0fzt1%28v=vs.100%29.aspx
In addition to the points made by KnowledgeSeeker, you can't create asp controls in that style.
You can either get the values of the created checkboxes by using the FindControl method to locate the element and then get the value from it or in the C# add code similar to:
for (int i = 0; i < 5; i++)
{
CheckBox chk = new CheckBox();
chk.ID = Convert.ToString(i);
chk.Text = Convert.ToString(i);
form1.Controls.Add(chk);
}
In that instance you are looping from 0 to 5 and creating checkboxes and adding those controls to the form.