Trying to use id generated dynamically in asp.net - c#

I am trying to use the id generated dynamically in asp.net.
<tr id="stdColTr" runat="server">
<td style="font-size:10pt">
<b>Nominal Tol(<asp:Label id="lblStdSize_Unit" runat="server" Text=""></asp:Label>)</b>
</td>
<td>
<asp:Label id="lblStdSize_Toler" runat="server" Text=""></asp:Label>
</td>
</tr>
I have a label in uw.aspx and I am trying to bind the table in it and trying to check whether if value read from database is zero then that particular td should not be visible in that table.
uw.aspx.cs
lblStdSize_Toler.Text = "<table ><thead><tr><th colspan='2'>Diameter</th><th colspan='2'>Tolerance</th></tr></thead><tr><td id='STd1'>From</td><td id='STd2'>To</td><td id='STd3'>+</td><td id='STd4'>-</td></tr>";
while (ReadData.Read())
{
prop_name = ReadData["prop_name"].ToString();
t_property = ReadData["tprop"].ToString();
}
lblStdSize_Unit.Text = ReadData["WD_PROP"].ToString();
if (prop_name == "1sizMin")
{
if (t_property=="0")
{
first td with id SD1 should be hidden.
}
lblStdSize_Toler.Text = lblStdSize_Toler.Text + "<td>" + tdc_property + "</td>";
}
Similarly remaining td checked with t_property if value is "0" then it should be visible false.

If I understand you correctly this should do what you need. It creates a row per recordset returned an applies a style (visibility) to the first column (STd1). I don't know anything about the code environment and I also just added the code as I think it could work. Please adjust variable names or typos to your liking.
lblStdSize_Toler.Text = "<table ><thead><tr><th colspan='2'>Diameter</th><th colspan='2'>Tolerance</th></tr></thead>";
while (ReadData.Read())
{
var row = "<tr><td id='STd1' style='visibility: {0};'>From</td><td id='STd2'>To</td><td id='STd3'>+</td><td id='STd4'>-</td></tr>";
var visibility = "visible";
prop_name = ReadData["prop_name"].ToString();
t_property = ReadData["tprop"].ToString();
lblStdSize_Unit.Text = ReadData["WD_PROP"].ToString();
if (prop_name == "1sizMin")
{
if (t_property=="0")
{
visibility = "hidden";
}
}
lblStdSize_Toler.Text += string.Format(row, visibility) + "<td>" + tdc_property + "</td>";
}

Related

How to show checkboxes to user that are saved as yes in database at frontend?

This is my grid which is dynamic. It is saving customer description against each checkbox. That is, if I mark the checkbox against Individual then it saves Y in my database otherwise N. so Now I just want to show tick on checkboxes that are saved Y in the database. Below is the code for my dynamic grid:
public string getCustomerStateGrid()
{
string html = ""; int Count = 1;
DataTable dt = getDataTableFromQuery(#"select Id,cuscheckbox,CustomerDescription from CustomerState3");
html = "<h2> Customer State </h2><br/><table class=\"display unbreakable\" id=\"tblCustomerDetail\" style=\"width:100%; border-collapse: collapse;\"><thead>";
#region Header
html += "<tr><th height='40' class=\"Greyheader\" style=\"width:5%\">S.No</th>";
html += "<th height='40' class=\"Greyheader\" style=\"width:30%\">Customer Status</th>";
html += "<th height='40' class=\"Greyheader\" style=\"width:15%\">Customer Description</th>";
//html += "<th class=\"Greyheader\" style=\"width:12%\">Action</th>";
html += "</tr></thead>";
#endregion
#region Body
html += "<tbody>";
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
html += "<tr class=\"GreyBorder\" id='tblCustomerDetail_" + dr["Id"].ToString() + "' pkid=\"" + dr["Id"].ToString() + "\" class=\"DataRow\">";
html += "<td class=\"GreyBorder\" style=\"text-align:center !important;\">" + Count + "</td>";
html += "<td class=\"GreyBorder\"><input id='txtcuscheckbox_" + dr["Id"].ToString() + "' type=\"checkbox\" style=\" text-align: right; width:95;\" value='" + dr["cuscheckbox"].ToString() + "' class=\"mediumTextField Customer Status\" /></td>";
html += "<td class=\"GreyBorder\"><input id='txtCustomerDescription_" + dr["Id"].ToString() + "' type=\"textbox\" style=\" text-align: right; width:95;\" value='" + dr["CustomerDescription"].ToString() + "' class=\"mediumTextField Customer Description\" /></td>";
html += "</tr>";
Count++;
}
}
else
{
html += "<tr class=\"GreyBorder\" ><td style=\"text-align:center !important;\" class=\"GreyBorder\" colspan='6'>No Data.</td></tr>";
html += "</tr>";
}
html += "</tbody>";
#endregion
html += "<tfoot><tr class='GreyBorder'>";
html += "<td class='GreyBorder' colspan='2'></td> ";
html += "</tr></tfoot>";
html += "</table><br/>";
return html.ToString();
}
I just want to customize this line of code
html += "<td class=\"GreyBorder\"><input
id='txtcuscheckbox_" + dr["Id"].ToString() + "'
type=\"checkbox\"
style=\" text-align: right; width:95;\" value='" + d
dr["cuscheckbox"].ToString() + "' class=\"mediumTextField
Customer Status\" /></td>";
so that it shows tick on checkbox. Can anyone modify my code to achieve this result? Is there any way we can do using ternary operator?
Well in essence you need:
var isChecked = 'Y';
html += isChecked == 'Y' ? "<input type=\"checkbox\" checked>" : "<input type=\"checkbox\">";
However, you are mixing front-end with back-end logic. Wouldnt it better to create a JSON endpoint that returns the data to the front-end and have the front-end generate the HTML?
EDIT:
To modify the current logic you could replace the line for creating the textbox with something like this:
var isChecked = dr["cuscheckbox"].ToString().ToUpper() == "Y" ? "checked" : string.Empty;
html += $"<td class=\"GreyBorder\"><input id='txtcuscheckbox_{dr["Id"].ToString()}' type=\"checkbox\" style=\" text-align: right; width:95;\" class=\"mediumTextField Customer Status\" {isChecked}/></td>";

populating HTML Radio buttons from code behind in C#

I am generating radio buttons from Code Behind in the following code
var licRB = questions[QNo - 1].AnswerRadioButton.optionRB;
for (int i = 0; i < licRB.Length; i++)
{
if (licRB[i]._checked == "true")
{
stringBuilder.Append(String.Format("<input type=\"radio\" name=\"Q" + (QNo) + "AnswerRBOption\" value='{0}' title='{1}' checked=\"checked\" />{1} <br />", licRB[i].value, licRB[i].text));
}
else
{
stringBuilder.Append(String.Format("<input type=\"radio\" name=\"Q" + (QNo) + "AnswerRBOption\" value='{0}' title='{1}' />{1} <br />", licRB[i].value, licRB[i].text));
}
}
(FindControl("divQ" + QNo + "AnswerRBL") as HtmlGenericControl).InnerHtml = stringBuilder.ToString();
On submit button click the value selected is stored in the db as follows:
ARBValue = Request.Form["Q" + QNo + "AnswerRBOption"],
Now I need to retrieve the value from the DB and show the radio buttons with the selected value. Pls let me know best way to do this?
Below text resolves the issue of showing the selected radio button in the HTML5 radio button list
(FindControl("divQ" + q.QNo + "AnswerRBL") as HtmlGenericControl).InnerHtml = q.ARBOption
.Replace("checked=\"checked\"","")
.Replace("value='"+ q.ARBValue + "'" , "value='" + q.ARBValue + "' checked=\"checked\"");

How to populate HTML table with SPQuery result

I've just started playing with developing in SP2010, so I'm complete begginer .
I've created simple console application with code like this :
using (SPSite currentSite = new SPSite("http://win-e9840laitme"))
{
using (SPWeb currentWeb = currentSite.OpenWeb())
{
SPList myList = currentWeb.Lists["List1"];
string currentUserName = currentWeb.CurrentUser.Name;
SPQuery queryInformationAboutCurrentUser = new SPQuery();
queryInformationAboutCurrentUser.Query = "<Where>" +
"<Eq><FieldRef Name='EmployeeName'/><Value Type='Text'>" + currentUserName + "</Value></Eq>" +
"</Where>";
List<EmployeeInfo> listEmployeeInfo = new List<EmployeeInfo>();
SPListItemCollection collectionEmployee = myList.GetItems(queryInformationAboutCurrentUser);
foreach (SPListItem info in collectionEmployee)
{
EmployeeInfo eInfo = new EmployeeInfo();
eInfo.Deparment = info["Office"].ToString();
listEmployeeInfo.Add(eInfo);
}
foreach (EmployeeInfo eI in listEmployeeInfo)
{
SPQuery querySameOffice = new SPQuery();
querySameOffice.Query = "<Where>" +
"<Eq><FieldRef Name='Office'/><Value Type='Choice'>" + eI.Deparment + "</Value></Eq>" +
"</Where>";
SPListItemCollection collectionEmployeeDisplay = myList.GetItems(querySameOffice);
foreach (SPListItem item in collectionEmployeeDisplay)
{
Console.WriteLine(item["EmployeeName"].ToString() + " " + item["PhoneNumber"].ToString() + "\n");
}
}
}
}
Now I want to use that code inside sharepoint project , and instead of putting result of SPQuery on Console , I want to populate HTML table with the result staticly(without JS or Jquery , if it is possible).
I've created sp project and added ApplicationPage.
My idea was to use StringBuilder and something like this :
StringBuilder html = new StringBuilder();
html.Append("<table border = '1'>");
//Building the Header row.
html.Append("<tr>");
html.Append("<th>");
html.Append("EmployeeName");
html.Append("</th>");
html.Append("<th>");
html.Append("PhoneNumber");
html.Append("</th>");
html.Append("</tr>");
and in the last foreach loop this code :
foreach (SPListItem item in collectionEmployeeDisplay)
{
html.Append("<tr>");
html.Append("<td>");
html.Append(item["EmployeeName"].ToString());
html.Append("</td>");
html.Append("<td>");
html.Append(item["PhoneBook"].ToString());
html.Append("</td>");
html.Append("</tr>");
}
//Table end.
html.Append("</table>");
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
I beleive there are more elegant solutions to this problem, and if you now it please give me idea .Thank you.
I've found a solution.First we need to add Repeater into PlaceHolderMain :
<asp:Repeater ID="rptEmployees" runat="server">
<HeaderTemplate>
<table border="1" style="width:70%">
<tr>
<td>Employee Name</td>
<td>Phone Number</td>
<td>Position</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("EmployeeName") %></td>
<td><%# Eval("PhoneNumber") %></td>
<td><%# Eval("Position") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
than create another class and add this code into final loop:
foreach (SPListItem item in collectionEmployeeDisplay)
{
DisplayEmployee dE = new DisplayEmployee();
dE.EmployeeName = item[Sol.PB1.Fields.EmployeeName].ToString();
dE.PhoneNumber = item[Sol.PB1.Fields.PhoneNumber].ToString();
dE.Position = item[Sol.PB1.Fields.Position].ToString();
display.Add(dE);
}
rptEmployees.DataSource = display;
rptEmployees.DataBind();
}
You cant use XSLT transformation to convert your SPQuery results to an HTML table. see example of Applying an XSLT Transform to a DataSet

Not able to see my linkbutton control inside a <td> element

Please check the below code, where I am able to generate the table dynamically from the database. But not able to display the link button inside the <td> element.
The basic function is to generate a new <tr> for every row in the database table with a link button added.
Aspx Code
<div style="width: 80%;" id="div_post" runat="server">
</div>
Aspx.cs Code
protected void GetvicharData()
{
try
{
Data_display dd = new Data_display();
DataTable dt = dd.disp_vichar();
string in_html = string.Empty;
int i = 0;
in_html = "<table style=\"width: 100%;\">";
foreach (DataRow dr in dt.Rows)
{
string str_build = string.Empty;
i = i + 1;
string lbDate = Convert.ToDateTime(dr["Date"]).ToString("dd-MMM-yy");
string lbTopic = dr["Topic_Name"].ToString();
string desc = dr["Description"].ToString();
string imgURL = dr["img_url"].ToString();
string textUrl = dr["txt_url"].ToString();
str_build = ret_string(lbDate, lbTopic, desc, imgURL, textUrl, i);
in_html += str_build;
}
in_html += "</table>";
div_post.InnerHtml = in_html;
}
catch (Exception ex)
{
throw ex;
}
}
public string ret_string(string lbldate, string lbltopic, string description, string imgurl, string texturl, int i)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("<tr><td class=\"post_date\" valign=\"top\" align=\"center\">");
sb.Append("<asp:Label ID=\"lblDate\" runat=\"server\">" + lbldate + "</asp:Label>");
sb.Append("</td><td class=\"post_topic\" valign=\"top\" >");
sb.Append(" <asp:Label ID=\"lblTopic" + i + "\" runat=\"server\">" + lbltopic + "</asp:Label>");
sb.Append("</td></tr><tr>");
sb.Append("<td class=\"ShowPic\" valign=\"top\" align=\"right\" ><img src=\"" + imgurl + "\" alt=\"\" id=\"img_post\" /></td>");
sb.Append("<td class=\"ShowPost\" valign=\"top\" style=\"text-align: justify\">");
sb.Append("<asp:Panel ID=\"pnlDesc" + i + "\" runat=\"server\"><p>" + description + "</p>");
sb.Append("</asp:Panel>");
sb.Append("<div><asp:LinkButton ID=\"lnkbtn" + i + "\" runat=\"server\" Text=\"Read more...\" onclick=\"lnkbtn1_Click\" OnClientClick=\"openNewWin('" + texturl + "')\" />");
sb.Append("</asp:LinkButton></div></td></tr>");
string sbuild = sb.ToString();
return sbuild;
}
catch (Exception ex)
{
throw ex;
}
}
As I am not able to figure it out that why my link button is showing hidden when I am rendering the page in the browser.
OK didn't test but,
sb.Append("</asp:LinkButton></div></td></tr>");
Where is the opening for the last </tr> ? . It seems to me its missing.
try sb.Append("</asp:LinkButton></div></td>"); instead
Also if it persist , try removing the last and putting it in a <tr><td> instead. One thing to put in mind also . Your ret_string method is in a a loop and therefore returns 1 row at a time. You can copy your ret_string method to an asp.net page and remove the C# codings, test and see if you have a successful row returned. Goodluck.
Update Also
OnClientClick=\"openNewWin('" + texturl + "')\" />");
Cn you try OnClientClick=\"openNewWin('" + texturl + "')\" >"); instead since i noticed you close the linkbutton in the next line already. So try remove the /> and see what happened?
Sorry Man. Just now when I see your code again It looks strange. I had to put another answer for i don't have any means of testing here. Like i mentioned in my previous answer, Your ret_string method is in a loop . Therefore your str_build should hold row ++ or one row at each loop instance. When you do like this..
foreach (DataRow dr in dt.Rows)
{
string str_build = string.Empty;
.................
str_build = ret_string(lbDate, lbTopic, desc, imgURL, textUrl, i);
in_html += str_build;
}
First str_build; hold one row in the first going. However, when it comes another round, you set string str_build = string.Empty; , this automatically cleared whih cever row the str_build; is holding if i understand your code clear. I am not sure how you get your rows returned by , but i had suggest you take out the
string str_build = string.Empty;
and put it before your loop like below
string str_build = string.Empty;
foreach (DataRow dr in dt.Rows)
{
.................
str_build = ret_string(lbDate, lbTopic, desc, imgURL, textUrl, i);
in_html += str_build;
}
Goodluck . try and see man....
I got my answer. Please check the code.
sb.Append("<a href=\"#\" onclick=\"openNewWin('" + texturl + "')\" >Read More...</a>");

Dynamically insert checkbox into a table in ASP.NET with variable number of fields. C# codebehind

I'm building an exemption request form that populates from an SQL Server 2008 database.
DataRow[] exemption = ds.Tables[2].Select();
foreach (DataRow dr in exemption)
{
string exemptionType = dr["ExemptionType"].ToString();
string exemptionID = dr["ExemptionID"].ToString();
string exemptionDesc = dr["ExemptionDescription"].ToString();
string displayLabel = dr["DisplayLabel"].ToString();
sb.Append("<table align='center' width='730px'>");
sb.Append("<tr><td><asp:CheckBox ID=\"chk" + exemptionID + "\" runat=\"server\" /></td>");
sb.Append("<td><strong>" + exemptionDesc + "</strong></td>");
sb.Append("</table>");
sb.Append("<table align='center' width='630px'>");
sb.Append("<tr><td>" + displayLabel + "</td></tr>");
sb.Append("</table>");
}
return sb.ToString();
As it stands right now, the table builds fine, all the data displays fine, but the checkbox does not show up. Was wondering if doing it this way is possible at all, and if so, what am I doing wrong?
You're inserting ASP.NET into your HTML and that HTML is probably not getting processed by ASP.NET. If you want to do it the way you're doing it now... switch to using input tags like so...
DataRow[] exemption = ds.Tables[2].Select();
foreach (DataRow dr in exemption)
{
string exemptionType = dr["ExemptionType"].ToString();
string exemptionID = dr["ExemptionID"].ToString();
string exemptionDesc = dr["ExemptionDescription"].ToString();
string displayLabel = dr["DisplayLabel"].ToString();
sb.Append("<table align='center' width='730px'>");
sb.Append("<tr><td><input type=\"checkbox\" id=\"chk" + exemptionID + "\" /></td>");
sb.Append("<td><strong>" + exemptionDesc + "</strong></td>");
sb.Append("</table>");
sb.Append("<table align='center' width='630px'>");
sb.Append("<tr><td>" + displayLabel + "</td></tr>");
sb.Append("</table>");
}
return sb.ToString();
The other route would be to actually create the ASP.NET Checkboxes. That would look somethig like this...
var checkbox = new CheckBox();
checkbox.ID = "chk" + exemptionId;
wrapper.Controls.Add(checkbox);
Where wrapper is a Panel or something of the sort.

Categories