How to find dynamic control inside a dynamically added container - c#

In my website I am uploading photos through asp:FileUpload [multiple files - images].. After uploading I am displaying them in a Panel along with a textbox to write description for the uploaded Images. Then am going to save them in database. But I am not able to find the values of the textbox or find the controls I have added to the panel when in my save event. But the images and textbox will be displayed in the panel.
My frontend code is something like this:
<form id="form1" runat="server">
<div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
<asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
<asp:Button runat="server" ID="uploadedFile" style="position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
<asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">
<asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" Font-Bold="true" BackColor="Yellow" />
</asp:Panel>
</div>
</form>
and my backend code is something like this:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
int tid = 0;
string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
{
HtmlGenericControl dh = new HtmlGenericControl("div");
dh.Attributes.Add("class", "head");
dh.InnerText = "Write Description";
updtpanel.Controls.Add(dh);
HtmlGenericControl dload;
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
tid = tid + 1;
textid = "txt" + tid;
Image img = new Image();
TextBox ta = new TextBox();
ta.TextMode = TextBoxMode.MultiLine;
filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
uploadedFile.SaveAs(filepath);
newpath = "../Images/Gallery/" + uploadedFile.FileName;
try
{
dload = new HtmlGenericControl("div");
updtpanel.Visible = true;
dload.Attributes.Add("class", "dataload");
dload.Attributes.Add("runat", "server");
dload.ID = "ind" + tid;
img.CssClass = "loadimg";
img.ImageUrl = newpath.ToString();
img.ID = "img"+tid;
img.Attributes.Add("runat", "server");
ta.Attributes.Add("class", "txtdes");
ta.ID = textid;
ta.Attributes.Add("runat", "server");
dload.Controls.Add(img);
dload.Controls.Add(ta);
updtpanel.Controls.Add(dload);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);
}
}
protected void btnsave_Click(object sender, EventArgs e)
{
foreach (Control c in updtpanel.Controls)
{
cnt1 += 1;
HtmlGenericControl div = ((HtmlGenericControl)updtpanel.FindControl("ind"+cnt1.ToString()));
foreach (Control nc in div.Controls)
{
string str = "";
string iurl = "";
TextBox txt = (TextBox)div.FindControl("txt" + cnt1.ToString());
Image img = (Image)div.FindControl("img" + cnt1.ToString());
str = txt.Text;
iurl = img.ImageUrl;
id += 1;
string Insert = "Insert into slider (slid,slurl,slalt) values (#id,#IMAGE_PATH,#alter)";
SqlCommand cmd = new SqlCommand(Insert, con);
cmd.Parameters.AddWithValue("#IMAGE_PATH", iurl);
cmd.Parameters.AddWithValue("#id", id);
cmd.Parameters.AddWithValue("#alter", str);
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception e1)
{
Response.Write(e1.Message);
}
}
}
updtpanel.Visible = false;
}
But its giving an error while saving which says object reference not set to an instance of the object after Findcontrol in save click event. Where I am going wrong. I am really working this from past 3 days but still not able to get it. Please show me a way out of this.
Is there anything else I need to add to this? I came across some site where some of them said that controls need to be recreated in Page_Load after postback. But when I am creating controls in an event How can I recreate them back in Page_Load.

Try this.Works for me try replacing the contentplaceholder with the form id may work.
String Value= (this.Form.FindControl("ContentPlaceHolder1").FindControl("panel").FindControl("txtbx" ) as TextBox).Text;

Related

Show all the values of selected items in a Text Box and find the Average of these values

Yes I tried using this operator technique, but On selecting 2 items from list box its giving me the sum of 3 or more items, Please let me know if the picture is visible to you..
Label1.Text = "";
foreach (int i in ListBox2.GetSelectedIndices()) {
Label1.Text += ListBox2.Items[i].Text + ",";
TextBox2.Text += ListBox2.Items[i] + "+";
}
Ok, I don't have your data, but lets just do this with say "id", and the Hotelname.
So, say this markup
<div style="float:left">
<asp:Listbox ID="LBHotels" runat="server"
Width="200px"
AutoPostBack="True"
OnSelectedIndexChanged="LBHotels_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName" Height="182px" SelectionMode="Multiple" >
</asp:Listbox>
</div>
<div style="float: left;margin-left:20px">
<h3>Occurance</h3>
<asp:TextBox ID="txtOccr" runat="server" Width="220px"></asp:TextBox>
</div>
<div style="float:left;margin-left:20px">
<h3>Results</h3>
<div style="text-align:right">
Total: <asp:TextBox ID="txtTotal" runat="server" TextMode="Number"></asp:TextBox><br />
Avg: <asp:TextBox ID="txtAvg" runat="server" TextMode="Number"></asp:TextBox>
</div>
</div>
(used div's, just float them left against each other - a nice easy way to place things around on a web form).
Ok, then this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
LBHotels.DataSource = MyRstP(cmdSQL);
LBHotels.DataBind();
}
}
And I did set auto-postback for the list box.
So, this code:
protected void LBHotels_SelectedIndexChanged(object sender, EventArgs e)
{
string sValues = ""; // string list of values for display into text box
int intTotal = 0; // total value
int[] Choices = LBHotels.GetSelectedIndices();
for (int i = 0; i < Choices.Length;i++)
{
ListItem MyChoice = LBHotels.Items[Choices[i]];
if (sValues != "")
sValues += "+";
sValues += MyChoice.Value;
intTotal += Convert.ToInt32(MyChoice.Value);
}
txtOccr.Text = sValues;
txtTotal.Text = intTotal.ToString();
txtAvg.Text = "0";
if (intTotal > 0)
txtAvg.Text =
String.Format("{0:0.####}", (decimal)intTotal / Choices.Length);
}
And the result is now this:
:

Set text from code behind

I have set the label text as empty as it depend on the situation.
In ascx file I set as below code:
<td runat="server" id="tdAvailableD" class="text-center" style ="font-size: 12px">
<asp:Label ID="lblAvailable" runat="server" ForeColor="Red" Visible="true" Text=""></asp:Label></td>
In ascx.cs file I set as below code:
private void CheckQuantityError()
{
for (int i = 0; i < dlDiscountedProducts.Items.Count; i++)
{
{
DropDownList qty = (DropDownList)dlDiscountedProducts.Items[i].FindControl("ddlQuantity");
HiddenField productId = (HiddenField)dlDiscountedProducts.Items[i].FindControl("hdnProductID");
HiddenField discountRuleId = (HiddenField)dlDiscountedProducts.Items[i].FindControl("hdnDiscountRuleId");
//HiddenField AvailStatus = (HiddenField)dlDiscountedProducts.Items[i].FindControl("hdnAvailStatus");
//HtmlGenericControl spanAvailStatus = (HtmlGenericControl)dlDiscountedProducts.Items[i].FindControl("spanAvailStatus");
Label lblOutofStockError = (Label)dlDiscountedProducts.Items[i].FindControl("lblOutofStockError");
Label lblAvailable = (Label)dlDiscountedProducts.Items[i].FindControl("lblAvailable");
DCShoppingCartItem shoppingCartItem = new DCShoppingCartItem();
if (null != Product)
{
bool status = false;
try
{
using (new AcsServiceContextScope())
{
status = AcsServiceContextScope.Current.Products.GetAxStockAvailability(new GetStockAvailabilityRequest()
{
ModelNumber = Product.ModelNumber,
Quantity = 1,
ProductId = Product.Id
}).StockStatus;
}
}
catch (Exception ex)
{
Logging.EventLogger.LogEvent(ex);
}
if (status == true)
{
//spanAvailStatus.Attributes["class"] = "glyphicon glyphicon-remove";//available
lblAvailable.Visible = true;
lblAvailable.Text = "In Stock";
lblOutofStockError.Visible = true;
lblAlert.Visible = true;
}
else
{
//spanAvailStatus.Attributes["class"] = "glyphicon glyphicon-ok";//not available
lblAvailable.Visible = true;
lblAvailable.Text = "No Stock";
lblOutofStockError.Visible = true;
lblAlert.Visible = true;
//qty.BackColor = System.Drawing.Color.Yellow;
}
}
}
}
}
but the text not display in page.The function should show, if the item have quantity then it will show in stock.
Try keeping lblAvailable inside an update panel and try posting back the page.
The reason could be setting the text in label is not posted back to the page.
Check if the value is Coming to the lblAvailable properly.
If it is? then put the
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<td runat="server" id="tdAvailableD" class="text-center" style ="font-size: 12px">
<asp:Label ID="lblAvailable" runat="server" ForeColor="Red" Visible="true" Text=""></asp:Label></td>
</ContentTemplate>
</asp:UpdatePanel>
then in .cs use this
UpdatePanel.Update();
and remove Text and ForeColor properties rather do it from .cs
u can even give different colors
lblAvailable.ForeColor = System.Drawing.Color.Green;//or red when not in stock

Upload files in Gridview and display in the same row upon completion

I am trying to store files from a Gridview upload into a Folder using Asp.net.
This is my markup code to generate Upload column and The button and File Upload control.
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" CommandName="Upload" Text="OK" style=" color: #ff0000" OnClick="btnUpload_Click"/>
</ItemTemplate>
</asp:TemplateField>
I have my codebehind to handle btnUpload_Click as below:
protected void btnUpload_Click(object sender, GridViewCommandEventArgs e)
{
Response.Write("File has been passed");
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload4") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fleUpload = Path.GetExtension(fu.FileName.ToString());
if (fleUpload.Trim().ToLower() == ".xls" | fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fu.FileName.ToString()));
//Someting to do?...
}
else
{
upload = false;
// Something to do?...
}
if (upload)
{
// somthing to do?...
}
}
else
{
//Something to do?...
}
}
I am getting this error:
CS0123: No overload for 'btnUpload_Click' matches delegate
'System.EventHandl
Can somebody please help me?
You're binding both Command and Click event with your button. Your button code should be like this-
<asp:TemplateField HeaderText="Upload">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" EnableViewState="true" AllowMultiple="true" />
<asp:Button ID="btnUpload" runat="server" CommandName="Upload" Text="OK" style=" color: #ff0000"/>
</ItemTemplate>
</asp:TemplateField>
and from code behind capture the command not the event. like-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Write("File has been passed");
Button bts = e.CommandSource as Button;
Response.Write(bts.Parent.Parent.GetType().ToString());
if (e.CommandName.ToLower() != "upload")
{
return;
}
FileUpload fu = bts.FindControl("FileUpload1") as FileUpload;//here
if (fu.HasFile)
{
bool upload = true;
string fileName = Path.GetFileName(fu.PostedFile.FileName);
string fleUpload = Path.GetExtension(fu.PostedFile.FileName);
if (fleUpload.Trim().ToLower() == ".xls" || fleUpload.Trim().ToLower() == ".xlsx")
{
fu.SaveAs(Server.MapPath("~/UpLoadPath/" + fileName));
string uploadedFile = (Server.MapPath("~/UpLoadPath/" + fileName ));
//Someting to do?...
}
else
{
upload = false;
// Something to do?...
}
if (upload)
{
// somthing to do?...
}
}
else
{
//Something to do?...
}
}
above I'm assuming your gridview ID is GridView1. And another one your File Uploader control's ID was mismatched with your code behind. This should work.

Request.Form giving extra values from Dynamic Textboxes

i am working with dynamic TextBoxes and then Getting their Values in code behind file. I am creating these boxes using Javascript. my asp.net page code is
<script type="text/javascript">
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
return false;
});
});
</script>
</head>
<body>
<form id="form2" runat="server">
<h1>jQuery add / remove textbox example</h1>
<asp:TextBox runat="server" ID="txt1" type='text' name="textname" />
<asp:Panel runat="server" ID='TextBoxesGroup'>
</asp:Panel>
<asp:LinkButton ID="addButton" runat="server">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</body>
i have one Textbox shown on the page, which should shows only one values when no dynamic Textbox is created. My C# code is
protected void Button1_Click(object sender, EventArgs e)
{
string name = txt1.Text + ",";
if (TextBoxesGroup.Controls.Count > 0)
{
for (int i = 1; i <= TextBoxesGroup.Controls.Count; i++)
{
name += Request.Form["textbox" + i] + ",";
}
}
Label1.Text = name;
}
on asp:button click it should display all the values separated by (,). but it is only showing top 2 values, one of which is asp:Textbox and second is dynamic Textbox,, i want the values of all the Textboxes created dynamically, and when no dynamic textbox is added it should only show the value from asp:textBox... Thanks in Advance
Html input elements created through javascript on the client, are not going to be in TextBoxesGroup.Controls on the server.
Changes in the client DOM structure have no effect on the Page's Control tree. The only thing affected will be the content of HttpRequest during postback. One way to know how many dynamically created input elements contributed to Request.Form data is to pass this information as part of the request. This is why you will have to go with the hidden field suggestion. The hidden field value will bring back the count of client-side inputs. You have to set it in javascript every time you create a new input, read it in server-side code, convert to integer and use in your for loop.
Add
<asp:HiddenField runat="server" ID="txtDynamicCount" value="0" />
to the the markup inside form tag.
In javascript click event after counter++; line add
$("#txtDynamicCount").val(counter);
In Button1_Click:
int count;
if (!int.TryParse(txtDynamicCount.Value, out count))
count = 0;
for (int i = 1; i <= count; i++)
{
...
}
The important difference from the other answer is that textboxes (input elements) will not persist between form submits.
You cannot populate server controls in client side. Instead, you want to populate them from server. Here is the sample -
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:LinkButton ID="addButton" runat="server" OnClick="btnAdd_Click">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br/>
Posted Results: <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var ids = ControlIds;
foreach (var id in ids)
{
var textbox = (TextBox)PlaceHolder1.FindControl(id.ToString());
Label1.Text += textbox.Text + ", ";
}
}

When I click on submit button no function is called

in my website when I click a submit button it should show all the links in a textbox ,but my submit button is not working, noting happens when I click it. Here's my code. My submit button has onclient click property.
protected void btnRender_Click(object sender, EventArgs e)
{
string strResult = string.Empty;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url.Text);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
sr.Close();
}
strResult = strResult.Replace("<form id='form1' method='post' action=''>", "");
strResult = strResult.Replace("</form>", "");
//strResult = strResult.Replace("<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" /><html xmlns="http://www.w3.org/1999/xhtml">");
div.InnerHtml = strResult;
}
protected void btn_createlink_Click(object sender, EventArgs e)
{
var links = TextBox1.Text.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var link in links)
{
if (!IsLinkWorking(link))
{
//Here you can show the error. You don't specify how you want to show it.
TextBox2.Text += string.Format("{0}\nNot working\n\n ", link);
}
else
{
TextBox2.Text += string.Format("{0}\n working\n\n", link);
}
}
}
bool IsLinkWorking(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//You can set some parameters in the "request" object...
request.AllowAutoRedirect = true;
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return true;
}
catch
{
//TODO: Check for the right exception here
return false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
TextBox2.Text = "";
url.Text = "";
}
}
here is my client side code
here i have function called finda() .when client clicks on submit button it should call but this not happening
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
function finda() {
var a = document.getElementsByTagName("a");
var b = document.getElementById("TextBox1");
b.value = "";
for (var i = 0; i < a.length; i++) {
a[i] = a.length.value;
if (a[i] == null) {
alert("Their is no links");
}
else {
b.value = b.value + "\r\n\n" + a[i];
}
}
// window.open("http://www.fillsim.com");
window.close();
// window.open("WebForm3.aspx?req=" + b.value);
}
</script>
<script type = "text/javascript">
var defaultText = "http://www.example.com";
function waterMarkText(txt, evt) {
if (txt.value.length == 0 && evt.type == "blur") {
txt.style.color = "red";
txt.value = defaultText;
}
if (txt.value == defaultText && evt.type == "focus") {
txt.style.color = "green";
txt.value = "";
}
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" >
Enter the URL:<br />
<br />
<asp:TextBox ID="url" runat="server" Width="263px"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnRender" runat="server" Text="Page Render" OnClick="btnRender_Click" />
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClientClick="javascript:finda();" />
<asp:Button ID="btn_createlink" runat="server"
Text="Create link" OnClick="btn_createlink_Click" />
<asp:TextBox ID="TextBox2" runat="server" Height="371px" TextMode="MultiLine" Width="409px"></asp:TextBox>
<div class="ab" id="div" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Clear"
Width="71px" />
</div>
</form>
Your form tag should have runat="server" attribute so that ASP.NET postback events can be properly handled.

Categories

Resources