I'm trying to read a text file containing the name of the image, and display it opon pageload.
Let's say that the content in the text file is
Australia Picture101
Singapore Picture201
Following is the code i tried and it does not display the image.
tableString += "<table class='content_background' cellpadding='0' cellspacing='0'>";
foreach (string line in lines)
{
string[] country = line.Split(token2);
string[] image = country[1].Split(token);
string row = "<tr><td class='left_content'>" + country[0] + "</td>" +"<td><table><tr>";
tableString += row;
for (int i = 0; i < image.Length; i++)
{
---> string row2 = "<td class='right_content'> <asp:ImageButton ImageUrl='~/img/missing children pictures/" + "image[i]" + ".jpg'/>" + "</td>";
tableString += row2;
}
tableString += "</tr></table></td>";
}
tableString += "</tr></table>";
container.InnerHtml = tableString;
Is there any other way to do this ? Thanks in advance.
the screen shot is as follow
That's no button ! You're outputting non-parsed HTML - the ASP.NET engine does not parse that, it just sends the data as HTML to the client.
Instead, use
var btn = new ImageButton();
btn.ImageUrl = "~/img/missing children pictures/" + "image[i]" + ".jpg";
Panel1.Controls.Add(btn);
As an easy hack, you can use
string row2 = "<td class=\"right_content\"> <input type=\"button\" style=\"background:url('/img/missing%20children%20pictures/" + image[i] + ".jpg')\"/></td>";
If you want to generate HTML directly, then use HTML tags:
<a href="[Img_CLick Link]"><img src="[image path]"
alt="Click" border="0" /></a>
Put appropriate values in the square brackets.
Otherwise consider using asp:Table control and add rows/cells at run time.
Related
I have a window form application, inside this application, there have several textbox and want to replace the breakline and send out as email in one click. Since i have multiple textbox, instead of writing like this:
string text = textBox1.Text;
text = text.Replace("\n", "<br/>");
string text2 = textBox2.Text;
text2 = text2.Replace("\n", "<br/>");
...
string textBody ="<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text + "</td></tr>" +"<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>" + ...
is there any ways to replace the line in these textbox in one time?
I try to put in a loop:
for (int i = 1; i < 20; i++)
{TextBox txtbox = (TextBox)this.Controls.Find("textBox" + i, true)[0]; }
I stuck at here. Any suggestion?
Your Form is a Control, which has a property Controls This property "Gets the collection of controls contained within the control".
You can use Enumerable.OfType to filter this so you get only the TextBoxes.
Is there any ways to replace the line in these textbox in one time?
You'll need a foreach to replace the text:
var textBoxesToUpdate = this.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxesToUpdate)
{
string proposedText = textBox.Text.Replace("\n", "<br/>");
textBox.Text = proposedText;
}
I also see this in your question
string textBody = "<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text1 + "</td></tr>"
+ "<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>"
+ ...
I don't know what you want with this. Consider to edit the question and change this.
I am trying to get a button out to my asp page:
Div1.InnerHtml += "<td><input type=\"submit\" ID=\"Button3\" runat=\"server\" OnClick=\"Button3_Click\" value = \"start\" ></button></td> ";`
The error "Button3_Click " but the error "0x800a1391 - Microsoft JScript runtime error: 'Button3_Click' is undefined" keeps coming out. Button3_Click is also used in the same environment and works there.
Edited
More information on the workings of my code
Step 1 ) Receive a string, splits it and forms a 2D array. All of which is done in c#
Step 2 ) Output is then sent to the ASP page to be displayed in a table. The table would would have 5 columns with n number of rows. The first 3 cols are data from the string above and the next 2 rows are buttons that manipulate the data.
Listed below are some code snippets
public void createarray(string results)
{
using (StringReader reader = new StringReader(results))
{
int lineNo = -1;
string line;
int columncount = 3;
Div1.InnerHtml += "<table border = \"1\" style = \" font- size:13px ; width:20% \" ;> ";
while ((line = reader.ReadLine()) != null)
{
++lineNo;
twodarray(lineNo, columncount, line);
}// while
}// using
Div1.InnerHtml += "</table>";
}// end of function
public Array[] twodarray(int rowcount, int columncount, string parts)
{
string[,] twoD = new string[10000, 10];
string[] parts2 = parts.Split(new string[] { "," }, StringSplitOptions.None);
int y = rowcount;
for (int x = 0; x < columncount; x++)
{
twoD[y, x] = parts2[x];
}
Div1.InnerHtml += "<tr>";
Div1.InnerHtml += "<td>" + y + "</td>";
Div1.InnerHtml += "<td>" + twoD[y, 0].TrimStart('\\') + "</td>";
Div1.InnerHtml += "<td>" + twoD[y, 1] + "</td>";
Div1.InnerHtml += "<td>" + twoD[y, 2] + "</td>";
Div1.InnerHtml += "<td><input type = \"submit\" ID=\"Button4\" runat=\"server\" OnClick=\"retunthis\" Text=\"stop\">stop</submit></td> ";
Div1.InnerHtml += "</tr>";
return null;
}
The problem I am facing is that when the button is pressed there is no error message, there is no functions that are being processed.
At the moment I am just sending the data to the asp page through "innerhtml". is there a better way for be to display my output ?
Note: thanks to jack for editing my first question, and those who replies. <3
First you have an html tag mismatch. You are closing an input tag of type button with a button tag. This won't fix your error but promotes good syntax.
Karl's solution didn't work for me (I would have left a comment but I'm not a high enough reputation yet).
I tried a number of options, none of which do the trick. It appears that when ASP.NET renders HTML, it converts an asp:Button to an input type as you would expect but pulls out any submit events into scripts.
For example:
<asp:Button ID="Button3" Text="Start" runat="server" OnClick="Button3_Click" />
Renders to...
<input type="submit" name="ctl00$MainContent$Button3" value="Start" id="MainContent_Button3" />
Also rendered is...
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['ctl01'];
if (!theForm) {
theForm = document.ctl01;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
I don't know where the event information is stored (maybe the view state) but it seems you would have to add this linkage as well.
Might just be easier to add the button in the HTML from the outright. If that's not possible, maybe try a ListView instead of a div and add buttons to the ListView.
I want to create an HTML table with my c# program.
I've tried this:
internal string CreateMailBody(mailObj dataObj)
{
string body = string.Empty;
body +=
"Dear all, there is my new table:" +
"TableNo: " + dataObj.Obj.Table.TableNumber+ "<br /> <br />";
body += "<table border='1'><tr><th>Line No</th><th>Table</th><th>Description</th><th>Count</th><th>Met</th><th>something</th></tr>";
foreach (var item in dataObj.Table.TableLineCollection)
{
body += "<tr><td>" + item.LineNumber +"</td>";
body += "<tr><td>" + item.Table+"</td>";
body += "<tr><td>" + item.Description+"</td></tr>";
}
return body;
}
Will it give a better solution for this ?
You may mix StringBuilder using the method AppendFormat and string literals (# in from of a string, so you can write multiple lines).
StringBuilder body = new StringBuilder();
body.AppendFormat (
#"Dear all, there is my new table:
TableNo: {0} <br /> <br />
<table border='1'><tr><th>Line No</th><th>Table</th><th>Description</th><th>Count</th><th>Met</th><th>something</th></tr>"
, dataObj.Obj.Table.TableNumber);
foreach (var item in dataObj.Table.TableLineCollection)
{
body.AppendFormat(
#"<tr><td> {0}</td>
<tr><td> {1}</td>
<tr><td> {2}</td></tr>",
item.LineNumber, item.Table, item.Description);
}
i have a class named "row" that has 3 item {property,instance,degree}.
now i want to show my items or rows to user and if he changed the third part of class i edit it. this is my code of generating rows dynamically, numberOfInstance is number of rows.
<div id="hidden" class="hiddendiv">
<%
string matn = "";
for (int i = 0; i < numberOfInstance ; i++)
{
row r= new row();
r = a[i];
matn+= " <div class='CMSdiv'>";
matn += "<input id='Text"+i+"' class='labelhid' type='text'"+"value = '"+r.Property+ "'/>";
matn += "<input id='Text2" + i + "' class='labelhid' type='text'" + "value = '" + r.instance+ "'/>";
matn += " <select id='Select" +i+ "'class='drophid' runat='server'>";
matn += " <option value= '"+ "خیلی زیاد"+"'>خیلی زیاد" + " <option value= '"+"زیاد'"+">زیاد";
matn += " <option value='"+"متوسط'"+">متوسط";
matn += " <option value='" + "کم'" + ">کم";
matn += "</select>";
matn += "</div>";
Response.Write(matn);
matn = "";
}
%>
</div>
now if user clicked on select and choose one option, i get it's value and pour to r.degree in code behind. but whatever i did i couldn't find it in code behind and was null. these are my attempts:
var val = Request["Select" + i];
string selection = Request.Form["Select" + i];
hd = (HiddenField)Page.FindControl("Select" + i);
hd = (HiddenField)Control.FindControl("Select" + i);
You can't generate server side controls by Response.Write (More info here). So html elements that you are writing to output are client side controls not server side and cannot be found using the Page.FindControl method.
Consider using one of the server side controls like Repeater instead.
I am trying to show online train in my page without any refresh. So I think I have to use updatepanel. My panel should be updated every second.
Let explain my code.
I put this part of code in my page:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_Load">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
So I put an interval function to refresh my panel like this,
<script type="text/javascript">
$(function () {
setInterval("__doPostBack('<%=UpdatePanel1.ClientID%>', '');", 1000);
});
In my code behind I put all fetched data,
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
foreach (var t in OnlineTrainList)
{
Response.Write("<div id='train-box' style='margin-left:" + (t.XTrainLocation - 8) + "px;margin-top:" + t.YTrainLocation + "px;background:" + t.Train.TrainColor + "'>" +
"<span>" +
t.TrainId +
"</span>" +
"</div>");
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
Response.Write("<div class='CurrentColor-Sensor' style='margin-left:" + (sensor.XLocation - 1) + "px;margin-top:" + (sensor.YLocation + 8) + "px;background:" + color + "'></div>");
}
}
}
So my problem is the panel doesn't refresh .And my panel UpdatePanel1_Load just call one time.
So your code is:
foreach (var t in OnlineTrainList)
{
Response.Write("<div id='train-box' style='margin-left:" + (t.XTrainLocation - 8) + "px;margin-top:" + t.YTrainLocation + "px;background:" + t.Train.TrainColor + "'>" +
"<span>" +
t.TrainId +
"</span>" +
"</div>");
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
Response.Write("<div class='CurrentColor-Sensor' style='margin-left:" + (sensor.XLocation - 1) + "px;margin-top:" + (sensor.YLocation + 8) + "px;background:" + color + "'></div>");
}
}
first thing i must bring your attention to the id that you assign to all those divs, it must be unique and never the same. you could use an increment variable and append it to your div's id eg: div0, div1... etc
now lets have a look at the first row inside the loop. what it basically has, is a <span> nested inside a <div> and containing some attributes with text.
the Asp.Net way of handling elements would be object oriented instead of just html string:
protected void UpdatePanel1_Load(object sender, EventArgs e)
{
//clear the update panel
UpdatePanel1.ContentTemplateContainer.Controls.Clear();
//var to generate unique div id's
int divIDIncrement = 0;
foreach (var t in OnlineTrainList)
{
//increment the id generator
divIDIncrement++;
// create a a DIV element
HtmlGenericControl _tempDIV = new HtmlGenericControl("div");
//set the attributes for the div
_tempDIV.ID = "train-box" + divIDIncrement.ToString();
_tempDIV.Style["margin-left"] = (t.XTrainLocation - 8).ToString() + "px";
_tempDIV.Style["margin-top"] = t.YTrainLocation.ToString() + "px";
_tempDIV.Style["background"] = t.Train.TrainColor.ToString();
//create the inner span
HtmlGenericControl _tempSPAN = new HtmlGenericControl("span");
//set the span's innerText
_tempSPAN.InnerText = t.TrainId.ToString();
//add the span into the Div
_tempDIV.Controls.Add(_tempSPAN);
//add the Div into your UpdatePanel
UpdatePanel1.ContentTemplateContainer.Controls.Add(_tempDIV);
List<Sensor> PassedSensor = new List<Sensor>();
PassedSensor = SensorRepository.FindBy(i => i.CurrentTrainId == t.TrainId).ToList();
string color = TrainRepository.FindBy(i => i.Id == t.TrainId).First().TrainColor;
foreach (Sensor sensor in PassedSensor)
{
// create another div for the sub stuff
HtmlGenericControl _tempSubDIV = new HtmlGenericControl("div");
_tempSubDIV.Attributes["class"] = "CurrentColor-Sensor";
_tempSubDIV.Style["margin-left"] = (sensor.XLocation - 1).ToString() + "px";
_tempSubDIV.Style["margin-top"] = (sensor.YLocation + 8).ToString() + "px";
_tempSubDIV.Style["background"] = color.ToString();
//add the sub stuff to the update panel
UpdatePanel1.ContentTemplateContainer.Controls.Add(_tempSubDIV);
}
}
}