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>");
Related
I have the following function which truncates a SQL Server varchar column and adds it to a string:
public void Pp()
{
strSql = #""; //query
using (SqlConnection conn = new SqlConnection(gstr))
{
try
{
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
myDataSet = new DataSet();
da.Fill(myDataSet);
string specific = "";
string generic = "";
string strTemp = "";
foreach (DataRow r in myDataSet.Tables[0].Rows)
{
if (r["MessageText"].ToString().Length <= 65)
{
strTemp = r["MessageText"].ToString();
}
else
{
strTemp = TruncateLongString(r["MessageText"].ToString(), 65);
}
specific += "</b><span class='hoverText' title='" + r["MessageText"] + "'>" + strTemp + "...</span>";
strTemp = "";
}
lblMessage.Text = "<b>SPECIFIC MESSAGES:</b> <br />" + specific;
}
catch (Exception ce)
{
}
}
}
public string TruncateLongString(string str, int maxLength)
{
return str.Substring(0, maxLength);
}
If the r["MessageText"] contains an appostrophe, it cuts off anything after it. (full text: no way no way HERE we go again but this is not working. Is it? or Is it not? I can't be too sure though. Can someone please check.)
Here is an example of a live preview (the title is shown but gets cut off because of the apostrophe):
Here is the source (the apostrophe is shown in the purple box. Also the color coding gets out of whack due to the apostrophe, which means the code is not correct):
How can I ensure it doesn't escape any escape characters, e.g. ', /, \.
You need to encode the HTML first.
Call this.Server.HtmlEncode( str ). This will also protect against other special characters like & and <.
That said, you're using single-quotes for attribute delimiters but HtmlEncode only encodes double-quotes, so you need to change your code to this:
specific = String.Format( CultureInfo.InvariantCulture, #"</b><span class=""hoverText"" title=""" + this.Server.HtmlEncode( r["MessageText"] ) + """>" + strTemp + #"...</span>";
.Replace(" ' ", "\\' "); You will probably want to do the same with double quote as well.
this my code
private DataTable ParseTable(string html)
{
HtmlDocument doc = new HtmlDocument();
DataTable dt = new DataTable();
String[] datasc;
String[] valueTemp = new String[30];
int index;
doc.LoadHtml("<table><tr><td><p><input id=\"ControlGroupScheduleSelectView_AvailabilityInputScheduleSelectView_RadioButtonMkt1Fare7\" type=\"radio\" name=\"ControlGroupScheduleSelectView$AvailabilityInputScheduleSelectView$market1\" value=\"0~N~~N~RGFR~~1~X|QG~ 885~ ~~BTH~05/19/2014 07:00~KNO~05/19/2014 08:20~\" />Rp.445,000 ( N/Cls;4 )</p></td></tr></table>");
for (int z = 0; z < 4; z++)
{
var getInputSchedule = doc.DocumentNode.SelectNodes("//table//input");
datasc = new String[getInputSchedule.Count];
for (int i = 0; i < getInputSchedule.Count; i = i+1)
{
string removeClassFare = string.Empty;
String[] selectValueSplit = getInputSchedule[i].Attributes["value"].Value.Split('|');
valueTemp[i] = selectValueSplit[1];
String[] getAlphaSC = selectValueSplit[0].Split('~');
try
{
index = getInputSchedule[i].ParentNode.InnerText.IndexOf("(");
if (index != -1)
{
removeClassFare = getInputSchedule[i].ParentNode.InnerText.Substring(0, index);
removeClassFare = System.Text.Encoding.ASCII.GetString(System.Text.Encoding.ASCII.GetBytes(removeClassFare)).Replace("??", "").Replace("Rp.", "").Trim();
}
}
catch (Exception e) {
//removeClassFare = getInputSchedule[i].ParentNode.InnerText;
}
if (!dt.Columns.Contains(getAlphaSC[1]))
{
dt.Columns.Add(getAlphaSC[1], typeof(string));
}
if (i == 0)
{
datasc[i] = "<div align=\"center\"><input <input onclick='faredetail(this.value, this.name)' id=\"" + getInputSchedule[i].Attributes["id"].Value + "\" type=\"radio\" value=\"" + getInputSchedule[i].Attributes["value"].Value + "\" name=\"" + getInputSchedule[i].Attributes["name"].Value + "\"><br>" + removeClassFare + "</div>";
}
else
{
if (selectValueSplit[1].Equals(valueTemp[i - 1],StringComparison.Ordinal))
{
datasc[i] = "<div align=\"center\"><input <input onclick='faredetail(this.value, this.name)' id=\"" + getInputSchedule[i].Attributes["id"].Value + "\" type=\"radio\" value=\"" + getInputSchedule[i].Attributes["value"].Value + "\" name=\"" + getInputSchedule[i].Attributes["name"].Value + "\"><br>" + removeClassFare + "</div>";
}
else
{
break;
}
}
getInputSchedule[i].Remove();
}
datasc = datasc.Where(x => !string.IsNullOrEmpty(x)).ToArray();
dt.Rows.Add(datasc);
}
return dt;
}
if i run, error message "Object reference not set to an instance of an object.", but if i remove the ID of element like
doc.LoadHtml("<table><tr><td><p><input type=\"radio\" name=\"ControlGroupScheduleSelectView$AvailabilityInputScheduleSelectView$market1\" value=\"0~N~~N~RGFR~~1~X|QG~ 885~ ~~BTH~05/19/2014 07:00~KNO~05/19/2014 08:20~\">Rp.445,000 ( N/Cls;4 )</p></td></tr></table>");
Everything works ok.
Why does the ID attribute cause my XPath to fail?
pleasee..help..
thank you
I stand corrected. SelectNodes does return null if it can't find any nodes.
But the behavior you are witnessing has nothing to do with the id attribute (in fact, removing the id attribute causes an exception to happen sooner), and everything to do with your code.
At the end of your inner loop, you are doing this:
getInputSchedule[i].Remove();
which removes the <input> element from the HTML document.
Your outer loop is set up to execute four times, so the second time it executes, the input element is already gone, and doc.DocumentNode.SelectNodes("//table//input") returns null, and that is the cause of your error.
I'm not really sure why you're removing the input elements from the document as you go through it, or why you're looping through the whole thing 4 times, but hopefully that gets you going in the right direction.
I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code txtOption2.Text = coldata[2];
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('$');
txtQuestion.Text = coldata[0];
txtOption1.Text = coldata[1];
txtOption2.Text = coldata[2];
txtOption3.Text = coldata[3];
txtOption4.Text = coldata[4];
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
thank you in advance for any help
You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns i.e.
string[] coldata = columns.Split("~")
You are seeing that error because you only have 2 items in coldata. Try debugging and view the length of the coldata array to see how many items it contains.
Change your code to use this split instead:
string[] coldata=columns.Split('~');
Looking at your code sample you just need to change:
string[] coldata=columns.Split('$');
To
string[] coldata=columns.Split('~');
As your columns are delimited by the ~ character.
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.
I am currently developing an application in C# where I need to read the values of the cell of each row in a DataGridView in C#.
foreach (DataGridViewRow row in tblCategories.Rows)
{
string folderPath = tblBackups.Rows[row].Cells[5].Value.ToString();
string backupIncludes = tblBackups.Rows[row].Cells[4].Value.ToString();
Console.WriteLine("Folder Path: " + folderPath);
Console.WriteLine("Backup Includes: " + backupIncludes);
}
For some reason, this is not working.
I managed to find out the problem for myself.
I changed the code to the following:
foreach (DataGridViewRow row in tblCategories.Rows)
{
string folderPath = row.Cells[5].Value.ToString();
string backupIncludes = row.Cells[4].Value.ToString();
Console.WriteLine("Folder Path: " + folderPath);
Console.WriteLine("Backup Includes: " + backupIncludes);
}
Thanks for your help