can not find dynamic html select in code behind - c#

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.

Related

C# ASP.NET Wrap dynamically added CheckBox Control with a dynamically added Label Control

I want the checkbox wrapped in a label so that if they click the Label it will check the CheckBox. I also need the descArea to diplay once the hover over the Label. These must also be dynamic and created in the code behind. I have 2 ways so far, both with their own issue...
This option doesn't allow the JS functions to be called for the descArea to slide down
caPanel.Controls.Add(new LiteralControl(
"<div class='col-md-6'>"+
"<div id='AButton" + t.Rows[i]["ID"].ToString() + "' class='caLabel' onmouseenter='slideDescriptionDown(this.id);' onmouseleave='slideDescriptionDown(this.id);' >" +
"<label>"));
CheckBox aCheckBox = new CheckBox();
aCheckBox.ID = "checkbox" + t.Rows[i]["ID"].ToString();
caPanel.Controls.Add(aCheckBox);
ca.Controls.Add(new LiteralControl(" " + t.Rows[i]["NAME"].ToString() +
"</label>"+
"</div>"+
"<div class='alert alert-info aDescription' id='descArea" + t.Rows[i]["ID"].ToString() + "'>" +
"<span id='desc" + t.Rows[i]["CA_ID"].ToString() + "'>" + t.Rows[i]["Description"].ToString() + "</span>" +
"</div>"+
"</div>"));
This one doesn't allow the CheckBox to be checked when clicking the Label. I inspected the code and the Label is showing up as a span
caPanel.Controls.Add(new LiteralControl("<div class='row caSectionRow'>" +
"<div class='col-md-6'>"));
Label aName = new Label();
aName.ID = "AButton" + t.Rows[i]["ID"].ToString();
aName.Attributes.Add("class", "caLabel");
aName.Attributes.Add("onmouseenter", "slideDescriptionDown(this.id);");
aName.Attributes.Add("onmouseleave", "slideDescriptionDown(this.id);");
aName.Text = " " + t.Rows[i]["NAME"].ToString();
CheckBox aCheckBox = new CheckBox();
aCheckBox.ID = "checkbox" + t.Rows[i]["ID"].ToString();
caPanel.Controls.Add(aCheckBox);
caPanel.Controls.Add(aName);
caPanel.Controls.Add(new LiteralControl(
"<div class='alert alert-info aDescription' id='descArea" + t.Rows[i]["ID"].ToString() + "'>" +
"<span id='desc" + t.Rows[i]["ID"].ToString() + "'>" + t.Rows[i]["Description"].ToString() + "</span>" +
"</div>" +
"</div>"));
I found the error lied within the JS function itself when trying to display the descArea for the first option I proposed. I didn't have the ID for the descArea correct. It was prepended with the MainContent_aContent_ to fulfill UniqueID property all controls must have in ASP.NET.
When is the ctl00 prefix added?
https://msdn.microsoft.com/en-us/library/1d04y8ss(v=vs.100).ASPX

C# WebBrowser click submit button with no response

This is my first time asking questions on StackOverflow, and I will be as much specific as I can.
When I opened the website with my Chrome, Firefox and IE, the submit button 'upgrade' works fine after I selected a file to upload/upgrade to the server (my router).
But when I'm trying it on my C# Winform project using the "WebBrowser" component, the submit button doesn't response at all (after I selected the file) whether I'm manually clicking the button or writing C# code to trigger the onClick event.
Does anyone have a clue? Any help would really be appreciated, thanks!
P.S. I'm sorry I can't provide to much picture about the webpage because I'm currently working under a company.
This is the what the webpage looks like
The html code of the webpage is showed below:
<table>
<td>
<label class="subtt2" style="margin-bottom:8px;font-size:14px">
Software Image:
</label>
</td>
<td>
<div class="file-box">
<input id="firmware" name="fupgrade.bin" class="file"
onchange="getfileName()" type="file" style="cursor:pointer">
<input id="filename" class="txt" type="text">
<input class="btnWtn" value="Browse" type="button">
<label class="error" id="lupgradeforbidden" style="display: none"></label>
</div>
</td>
</table>
<div class="buttonStyle" align="left">
<input name="UPLOAD_ACTION" id="UPLOAD_ACTION" value="Upgrade"
onclick="upgradeRouter()" type="button">
</div>
The upgradeRouter() is as follows:
function upgradeRouter()
{
var FIRMWARE = document.getElementById( "firmware" );
var UPLOAD_ACTION = document.getElementById( "upload_action" );
if( FIRMWARE.value == "" )
alert( "Please select firmware file" );
else
{
fileSize = FIRMWARE.files.item(0).size;
if(fileSize > 0)
{
if( uploading == 0 )
{
document.forms["myForm"].submit();
setTimeout("firmware_update_query_request();", POLLING_FW_STATUS_SECONDS*1000);
document.getElementById('upgradeFrame').style.display = 'none';
document.getElementById('upgradeModalBox').style.display = 'block';
UPLOAD_ACTION.value = "Cancel";
uploading = 1;
}
else
{
uploading = 0;
UPLOAD_ACTION.value = "Update";
myForm.reset();
}
}
}
return false;
}
Since fileSize = FIRMWARE.files.item(0).size; crash (which leads to clicking the upgrade button with no repsonse), the work around solution to my problem is just to inject script into the web page and execute my version of upgradeRouter() again.
Which I set up the value of fileSize manually beforehand.
The injection code is shown below
public void InjectScript()
{
HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptElement.DomElement;
element.text = "function upgradeRouter_M()" +
"{ " +
"var FIRMWARE = document.getElementById(\"firmware\"); " +
"var UPLOAD_ACTION = document.getElementById(\"upload_action\");" +
" if (FIRMWARE.value == \"\")" +
" alert(\"Please select firmware file\");" +
" else" +
"{" +
"fileSize = 47599364;" +
"" +
"if (fileSize > 0)" +
"{" +
"if (uploading == 0)" +
"{" +
"document.forms[\"myForm\"].submit();" +
"setTimeout(\"firmware_update_query_request();\", POLLING_FW_STATUS_SECONDS * 1000);" +
"document.getElementById('upgradeFrame').style.display = 'none';" +
"document.getElementById('upgradeModalBox').style.display = 'block';" +
"UPLOAD_ACTION.value = \"Cancel\";" +
"uploading = 1;" +
"}" +
"else" +
"{" +
"uploading = 0;" +
"UPLOAD_ACTION.value = \"Update\";" +
"myForm.reset();" +
"}" +
"}" +
"}" +
"}";
headElement.AppendChild(scriptElement);
webBrowser1.Document.InvokeScript("upgradeRouter_M");
Console.WriteLine("Injection completed");
}

How to innerhtml out asp tags

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.

Loop Button inside the Loop Div

I'm new here, I'm stuck in problem in which i have to loop my button so that i will be able to put it on my looping div. How will I do that? This is what I got so far:
//my loop
for (i = 0; i < MPreply.recommendation.Length; i++) {
html += "<div class='rec'> ";
html += "</br> <div id = 'from1' value = > Depart From:" + " ";
html += emz + " " + "(" + + ")" + "</div>";
html += "<div id = 'date1' > Schedule:" + " " + flytDate;
html += " , " + convertedString;
html += "</div>" + "<div id = 'to1' >To:" + " " + emz2 + " " + "(" + "" + ")";
html += "</div> </br> </br> </br> ";
html += "<div id = 'RecNo'>" + " " + (i + 1) + " )" + " </br> </br> </div> ";
html += "<div id = 'fare1'> $" + em + " </div> ";
html += " </div> <br/> <br/>";
div_rec.InnerHtml = html;
}
html:
<div id = 'modal' runat="server" >
<div id="dialog" runat="server">
</div>
<input id="_menuitem" type="button" value="Click" runat="server" />
</div>
Thanks in advance.
You have at least a few problems:
"<div id = 'fare1'>
and similar sections will generate multiple elements with the same id.
div_rec.InnerHtml = html;
Should be moved outside of your loop so that div_rec is only updated once, when everything is done.
emz + " " + "(" + + ")" + "</div>";
Should (probably) be changed to
emz + " " + "(" + your_variable_here + ")" + "</div>";
In order to (I think) add the creation of a button in your loop, you'll have to piece it together as a string just like your other elements. To get a function handler wired up you'll have to either:
a) Build a dom level-0 handler as a string, or
b) Wait until your html is updated, then query out the newly added buttons and add event handlers in code (using either btn.onclick = function(... or dom level-2 handlers (addEventListener or attachEvent)
The Problem i see here is with the ID field.
You have mentioned same ID name for all the Div's you are generating.
Like,
<div id = 'from1'>
<div id = 'to1'>
ID is a unique identifier to an element. It must always be unique.
You can Use Class instead.
Like,
<div class = 'from1'>
<div class = 'to1'>

include button into .cs file

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.

Categories

Resources