How to read a checkbox value generated from a label? - c#

Hi, I'm facing this problem getting the value of the checkbox value that I generated from C# code in a label. The output is just as I wanted, but i've tried using the below codes, but the object tells me its value is null. Someone please guide me, I need help.
HtmlInputCheckBox MyCheckBox = new HtmlInputCheckBox();
MyCheckBox = (HtmlInputCheckBox)this.FindControl("Qn" + temp);
bool isChacked = MyCheckBox.Checked;
MyMethod
string table1 = "";
ArrayList listofquestionnonradio = DBManager.GetSurveyQuestionNonRadio();
ArrayList listofallquestion = DBManager.GetAllSurveyQuestions();
int lastcount = Convert.ToInt32(listofquestionnonradio.Count);
table1 = "<br/><table>";
foreach (SurveyQuestions surv in listofallquestion)
{
if (surv.Questionid <= listofquestionnonradio.Count)
{
//get questions without radio
table1 += "<tr><td><b>Q" + temp + ")</b></td><td>" + surv.Question + "</td></tr><tr><td valign=top>Ans:</td><td>";
foreach (string subjname in listofselectsubjectnames)
{
//get name from excludelist
bool result= DBManager.GetExcludedQuestionsByQidAndSubject(surv.Questionid, subjname);
if (result == false)
{
string subvalue = subjname + "_val";
table1 += "<input type=checkbox name=Qn" + counterqn + " value=" + subvalue + " >" + subjname + "<br>";
counterqn++;
}
}
table1 += "<input type=checkbox name=lastqn value=NIL)>All of the above<br/></td></tr>";
table1 += "<tr style=height:10px></tr>";
temp++;
}
else
{
//get questions id if they are disable
bool result= DBManager.GetExcludedQuestionsByQid(surv.Questionid);
if (result == false)
{
//get questions with radio
table1 += "<tr><td><b>Q" + temp + ")<b></td><td>" + surv.Question + "</td></tr><tr><td valign=top>Ans:</td><td>";
table1 += "<input type=radio name=Qn" + counterqn + " value=1>Strongly disagree<br><input type=radio name=Qn" + counterqn + " value=2>Disagree<br><input type=radio name=Qn" + counterqn + " value=3>Agree<br><input type=radio name=Qn" + counterqn + " value=4>Strongly agree<br><input type=radio name=Qn" + counterqn + " value=5>Not applicable<br></td></tr>";
table1 += "<tr style=height:10px></tr>";
}
else
{
temp--;
}
temp++;
}
}
table1 += "</table><br/>";

I think the reason why you cannot access the checkbox controls is because you are not actually using server controls, you are building up your markup yourself. Your WebForm therefore does not have any controls to find.
If you are using ASP.NET WebForms (which is what I'm assuming) then why don't you use the server controls to build your table rather than manually building the HTML? You would then be able to view/modify them in your code-behind.
Take a look at the GridView control for a start to see how you could build up a table/grid-view easier than what you are currently doing.

Related

how to join two tables in sql and showing the results event A then all attendees, Event B and showing all the attendees, etc

Good Afternoon All,
I am creating an admin page that shows a list of events and those who volunteered to help. I have one table for events and another for those who are volunteer.
I stored the eventID into the volunteer's table and am able to join them, but when i join them I get a new row for each volunteer which also shows the event name again.
I would like to display the event name and underneath the event name show the volunteers.
ex.
event A
Volunteer 1
volunteer 2
volunteer 3
event B
Volunteer 1
volunteer 2
Can anyone point me in the right direction?
public string volunteers(){
SqlCommand cmd = new SqlCommand(#"SELECT* FROM fundraiser_youth
LEFT JOIN
fundrasier_helpers ON fundraiser_youth.id = fundrasier_helpers.eventID
ORDER BY reportTime;", con);
con.Open();
SqlDataReader reader;
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime reportTime = Convert.ToDateTime(reader[1]);
DateTime gateTime = Convert.ToDateTime(reader[2]);
DateTime gameTime = Convert.ToDateTime(reader[3]);
VOLUNTEER.Append("<div class='col-md-4'>");
VOLUNTEER.Append("<div class='well well-lg'>");
VOLUNTEER.Append("<form action='register/default.aspx' method='POST'>");
VOLUNTEER.Append("<h4>" + reportTime.DayOfWeek + " " + reportTime.Month + "/" + reportTime.Day + "/" + reportTime.Year + "</h4>");
VOLUNTEER.Append("<h5>" + reader[4].ToString() + " " + reader[7].ToString() + " " + reportTime.ToString("h:mm tt", CultureInfo.InvariantCulture) + "</h5>");
VOLUNTEER.Append("<ul>");
VOLUNTEER.Append("<li>" + reader[10].ToString() + " " + reader[11].ToString() + "</li>");
VOLUNTEER.Append("</ul>");
VOLUNTEER.Append("<input type=hidden name='id' value='" + reader[8].ToString() + "' />");
VOLUNTEER.Append("<span style='text-align:right; margin-top:20px;'><input type='submit' value='Register' class='btn btn-info' /></span>");
VOLUNTEER.Append("</form>");
VOLUNTEER.Append("</div>");
VOLUNTEER.Append("</div>");
}
return VOLUNTEER.ToString();
}
return "no info provided";
}
The first aspect of your stated problem is the select list. Select * will return all columns of all joined tables in the query for each joined row. So, each of your helpers will have the fundraising event information as part of its row data.
One side note for maintenance: select * is a bad habit for "production code", especially if you're getting fields out of the result set by index (which you are), because if you add a field to fundraiser_youth, all the indexes representing fields from fundraiser_helpers will no longer line up with the result set being returned, and your UI and any validation logic on this field data will break. I recommend strongly that you either specify the list of desired columns explicitly, get them out of reader using the column names instead of index positions, or both.
Since you're digesting the results programmatically in C#, the easiest solution to your stated problem is to first change your ORDER BY clause so that rows are sorted by fundraiser_youth.id before anything else. Then, get the event information once on the first row, generate your event header and the first volunteer row in HTML, remember that event ID, and check it against the ID of subsequent rows as you iterate through the reader generating the rest of the volunteer HTML rows. As long as the event IDs match, ignore the event fields and only extract/display the helper fields. When they differ, the event has changed and you need to re-retrieve the event information for the next sub-header.
Here is how I ended up fixing my problem. May not be best option but it works, Thanks for everyone's input and in the production code I replaced the select * with the columns. I made a new function called (loadHelpers) and pass the id of the current Event to it. This function pulls all the volunteers who signed up to help.
public string volunteers()
{
SqlCommand cmd = new SqlCommand(#"SELECT * FROM fundraiser_youth WHERE reportTime >='" + DateTime.Now + "' ORDER BY reportTime" , con);
con.Open();
SqlDataReader reader;
try
{
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
DateTime reportTime = Convert.ToDateTime(reader["reportTime"]);
DateTime gateTime = Convert.ToDateTime(reader["gateTime"]);
DateTime gameTime = Convert.ToDateTime(reader["gameTime"]);
events.Append("<div class='col-md-4'>");
events.Append("<div class='well well-lg'>");
events.Append("<form action='register/default.aspx' method='POST'>");
events.Append("<h4>" + reportTime.DayOfWeek + " " + reportTime.Month + "/" + reportTime.Day + "/" + reportTime.Year + "</h4>");
events.Append("<h5>" + reader["eventName"].ToString() + " " + reader["location"].ToString() + " " + reportTime.ToString("h:mm tt", CultureInfo.InvariantCulture) + "</h5>");
events.Append(loadHelpers(reader["id"].ToString()));
events.Append("<!--<span style='text-align:right; margin-top:20px;'><input type='submit' value='Edit' class='btn btn-info' /></span>-->");
events.Append("</form>");
events.Append("</div>");
events.Append("</div>");
}
return events.ToString();
}
return "no info provided";
}
catch (Exception e)
{
return "ERROR" + e;
}
}
public string loadHelpers(string id)
{
var cmd2 = new SqlCommand(#"SELECT * FROM fundrasier_helpers WHERE eventID='"+ id + "'" , con2);
con2.Open();
if (cmd2.ToString() != "")
{
SqlDataReader reader2;
StringBuilder helper = new StringBuilder();
helper.Append("<ul>");
try
{
reader2 = cmd2.ExecuteReader();
if (reader2.HasRows)
{
while (reader2.Read())
{
helper.Append("<li>" + reader2["firstName"] + " " + reader2["lastName"] + " " + reader2["phone"] + " " + reader2["shirtSize"] + "</li>");
}
}
reader2.Close();
}
catch (Exception e)
{
helper.Append("<li>No volunteers have signed up " + e + "</li>");
}
helper.Append("</ul>");
con2.Close();
return helper.ToString();
}
else
{
return "<ul><li>No volunteers have signed up</li></ul>";
}
}

Add SQL row to a ASP label based on a condition

SQL Table:
ID CreatedDate MessageText CreatedBy IsActive ClientText LocationText ProviderText SpecialtyText
1 March 4, 2015 dsdfsdf Test1 False
2 March 4, 2015 dsdfsdf Test2 True
3 March 4, 2015 dsdfsdf Test2 True Test Client location1 Test2 MD
4 March 4, 2015 This is to add Test1 False Test Client location2 Test3 DD
Getting the table:
using (SqlConnection conn = new SqlConnection(gloString))
{
string strSql = #"SELECT * FROM [DB].[dbo].[table2]";
try
{
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
// this will query your database and return the result to your datatable
myDataSet = new DataSet();
da.Fill(myDataSet);
}
catch (Exception ce)
{
}
}
I have the following label in my ASP.net page: <asp:Label ID="lblMessage" Font-Size="x-small" runat="server" Text="" ClientIDMode="Static"></asp:Label>
How can I update the label like this:
lblMessage.Text += "<b>ALL MESSAGES:</b> <br />";
foreach (ROW WHERE COLUMN {CLIENTTEXT}, {LOCATIONTEXT}, {PROVIDERTEXT}, AND {SPECIALTYTEXT} IS EMPTY)
{
lblMessage.Text += {CREATEDDATE} + " - " + {MESSAGETEXT} + "<br /><br />";
}
lblMessage.Text += "<hr />";
lblMessage.Text += "<b>SPECIFIC MESSAGES:</b> <br />";
foreach (ROW WHERE COLUMN {CLIENTTEXT}, {LOCATIONTEXT}, {PROVIDERTEXT}, OR {SPECIALTYTEXT} IS NOT EMPTY)
{
lblMessage.Text += {CREATEDDATE} + " - " + {MESSAGETEXT} + "<br /><br />";
}
The way I get it, you want to update your label using the rows that dont contain a "SpecialityText". The problem is you dont know how.
Let's say the DataSet you use in your page is still named myDataSet after you fetch it, the following code should do the trick. Please note I assumed you have some data access namespace imported. DBNull.Value should be replaced with whathever the null representation your helper uses.
string specific = "";
string generic = "";
foreach (DataRow r in myDataSet.tables[0].Rows){
//Add all your conditions here. It seems you want two groups of messages
if (r["SpecialtyText"].ToString == ""){
generic += r["CreatedDate"] + " - " + r["MessageText"] + "<br /><br />";
}
else{
specific += r["CreatedDate"] + " - " + r["MessageText"] + "<br /><br />";
}
}
lblMessage.Text = generic + "<hr /><b>SPECIFIC MESSAGES:</b> <br />" + specific;
I don't see a difference for the 2 for loops you showed.
If it's just one table you should be using a DataTable instead of a DataSet
You can do it like this:
foreach (DataRow row in table.Rows)//table is a DataTable
{
var clientText = row["ClientText"].ToString();
var locationText = row["LocationText"].ToString();
var providerText = row["ProviderText"].ToString();
var specialtyText = row["SpecialtyText"].ToString();
var createdDate = row["CreatedDate"].ToString();
var messageText = row["MessageText"].ToString();
if (string.IsNullOrEmpty(clientText) &&
string.IsNullOrEmpty(locationText) &&
string.IsNullOrEmpty(providerText) &&
string.IsNullOrEmpty(specialtyText))
{
lblMessage.Text += createdDate + " - " + messageText + "<br /><br />";
}
}
then add else block if you need. You can also use linQ
foreach (var clientText in from DataRow row in table.Rows
let clientText = row["ClientText"].ToString()
let locationText = row["LocationText"].ToString()
let providerText = row["ProviderText"].ToString()
let specialtyText = row["SpecialtyText"].ToString()
where string.IsNullOrEmpty(clientText) &&
string.IsNullOrEmpty(locationText) &&
string.IsNullOrEmpty(providerText) &&
string.IsNullOrEmpty(specialtyText)
select clientText)
{
//some code here
}

Add lines below rows dynamically

I have written this code to send an email when an change is made in a gridview.
I send an email with changes made in the column in row format. I need to add a line below each row and I am using this code and it doesn't work.
I have used this part to add line below rows sbMsg.AppendFormat("<table rules=" + rows + " style=' font-family:Calibri;background-color:#F1F1F1' width='1000'>");
public string mailFormatting(string Code)
{
List<string> lstSpecificColumns = new List<string>();
DataTable dtCurrentTbl = activeApplication.LoadMailActiveApplications(Code.ToString().Trim());
DataTable dtOldTbl = activeApplication.LoadMailLogManualUpdatesDetails(Code.ToString().Trim());
for (int colIndex = 0; colIndex < dtCurrentTbl.Columns.Count; colIndex++)
{
if (!dtCurrentTbl.Rows[0][colIndex].ToString().Equals(dtOldTbl.Rows[0][colIndex].ToString()))
{
lstSpecificColumns.Add(dtCurrentTbl.Columns[colIndex].ColumnName);
}
}
dtCurrentTbl.Merge(dtOldTbl);
DataTable resultTbl = dtCurrentTbl.AsEnumerable().CopyToDataTable().DefaultView.ToTable(true, lstSpecificColumns.ToArray());
string rows = "\"rows\"";
StringBuilder sbMsg = new StringBuilder();
sbMsg.AppendFormat("<p><font color=gray>Title<font></p>");
sbMsg.AppendFormat("<table rules= + rows + style='font-family:Calibri;background-color:#F1F1F1' width='1000'>");
sbMsg.AppendFormat("<tr> <td colspan='2'> <font color=blue> <u> " + Code.ToString().Trim() + " </u></font><td></tr>");
foreach (DataColumn dc in resultTbl.Columns)
{
sbMsg.AppendFormat("<tr>");
sbMsg.AppendFormat("<td> " + dc.ColumnName.Trim() + " </td>");
sbMsg.AppendFormat("<td> <strike>" + resultTbl.Rows[1][dc].ToString().Trim() + "</strike>" + " " + resultTbl.Rows[0][dc].ToString().Trim() + " </td>");
sbMsg.AppendFormat("</tr>");
}
sbMsg.AppendFormat("</table>");
return sbMsg.ToString();
}
Can anyone help me in this.

Exporting rows to a text file from dataGridView in C# only exports first row

I want to export rows to a text file. Not all rows, but only rows that are checked in dataGridView when I click on the export button. My problem is my program exports only the first row entered, and only one time. When I check more than row in a condition of selected I have put a checkbox in cells of index 0. This is what my export button contains:
private void buttonExport_Click(object sender, EventArgs e)
{
System.IO.StreamWriter str = new System.IO.StreamWriter("fichier.txt");
dataa= dataset.Tables["Rech"];
str.WriteLine("NumRep " + " Description " + " DateRep " + " cout " + " Matricule " + " CodeRep " + " CodeTypeRep ");
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Selected == true) // checkbox checked
{
str.WriteLine(dataa.Rows[i][0] + " " + dataa.Rows[i][1] + " " +dataa.Rows[i][2]
+ " " +dataa.Rows[i][3] + " " + dataa.Rows[i][4] + dataa.Rows[i][5] + " " + dataa.Rows[i][6]);
}
}
str.Close();
}
I don't know where the problem is with my logic.
Try changing this:
if (dataGridView1.Rows[i].Cells[0].Selected == true) // checkbox checked
{
...
}
to this:
DataGridViewCheckBoxCell chkCell = dataGridView1.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
if (chkCell.Value.Equals(chkCell.TrueValue)) // checkbox checked
{
...
}
DataRow row DataGridView1.Row[i]
DataGridViewCheckBoxCell chk = row.Cells[0] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(chk.Value) == true)
You can try above to get what you needed out of DataGridView. It worked for me.
Good Luck!
I have changed my condition to this :
if ((bool)dataGridView1.Rows[i].Cells[0].Value == true)
and it worked for me.
thanks to all !!

ASP.Net C# request in retrieving values from input type textbox

So our group is having a problem in retrieving the values input at the input type. here is the code that we use...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session.Remove("clicks");
i = 0;
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int rowCount = 0;
rowCount = Convert.ToInt32(Session["clicks"]);
rowCount++;
Session["clicks"] = rowCount;
Literal1.Text = Literal1.Text + "PRODUCT: <input type='textbox' runat='server' id='textboxu" + i + "' value='" + GridView1.SelectedRow.Cells[1].Text + "' ></input> PRICE: <input type='textbox' runat='server' size='1' id='textboxe" + i + "' value='" + GridView1.SelectedRow.Cells[2].Text + "' ></input>QUANTITY:<input type='textbox' runat='server' size='1' id='textboxq" + i + "'></input>TOTAL:<input type='textbox' runat='server' size='3' id='total" + i + "' ></input><br>";
i++;
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int check = 0; check <= i; check++)
{
double price = Convert.ToDouble(this.Request.Form["textboxe" + i + ".Value"]);
double quantity = Convert.ToDouble(this.Request.Form["textboxq" + i + ".Value"]);
double total = price * quantity;
TextBox1.Text = Convert.ToString(total);
//this.Request.Form["total" + i] = Convert.ToString(total);
}
}
we need to retrieve the answer also from the input type. i hope there are someone who will be willing to help us...
These are not server controls, so you should use name attribute instead of id.
<input type='textbox' name='textboxu" + i + "' value='" + GridView1.SelectedRow.Cells[1].Text + "' ></input>
...
double textboxu = Convert.ToDouble(this.Request.Form["textboxu" + i]);
There is just slight change in syntax to get correct answer, see below snippet
double price = Convert.ToDouble(Request.Form["textboxe" + i ]);
double quantity = Convert.ToDouble(Request.Form["textboxq" + i]);
double total = price * quantity;
TextBox1.Text = Convert.ToString(total);
//you need to use only request.Form rather than .value attribute
string szValue = Request.Form["txt1"]
hope it helps

Categories