Is it possible to add a control dynamically inline with innerhtml? - c#

Does anyone know how I can add a control dynamically inline with innerhtml from code behind then capture the value when a button is clicked? Not sure how to explain this so I created example code.
.aspx
<div id="myTable" runat="server"></div>
<div id="result" runtat="server"></div>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
.cs
protected void Page_Load(object sender, EventArgs e)
{
GetTable();
}
protected void GetTable()
{
string name = "Sam";
string age = "18";
TextBox txtTags = new TextBox();
txtTags.ID = "txtBox1";
myTable.InnerHtml =
"<div>" +
"<div>" +
name +
"</div>" +
"<div>" +
Controls.Add(txtTags) +
"</div>" +
"<div>" +
age +
"</div>" +
"</div>";
}
protected void btnSave_Click()
{
string myTextbox = txtBox1.Text;
result.InnerHtml = "Result: " + myTextbox;
}

Alright I figured it out.
TextBox txtFileTags = new TextBox();
txtTags.ID = "txtBox1";
HtmlGenericControl parent1 = new HtmlGenericControl("div");
HtmlGenericControl child1 = new HtmlGenericControl("div");
HtmlGenericControl child2 = new HtmlGenericControl("div");
HtmlGenericControl child3 = new HtmlGenericControl("div");
HtmlGenericControl child4 = new HtmlGenericControl("div");
child1.InnerHtml = "Sam"
parent1.Controls.Add(child1);
child2.Controls.Add(txtTags);
parent1.Controls.Add(child2);
child3.InnerHtml = "18";
parent1.Controls.Add(child3);
myTable.Controls.Add(parent1);

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetTable();
}
}
void GetTable()
{
string name = "Sam";
string age = "18";
string input = $#"
<div>
<div>{name}</div>
<div><input type='text' name='txtBox1' value='' /></div>
<div>{age}</div>
</div>";
myTable.InnerHtml = input;
}
protected void btnSave_Click(object sender, EventArgs e)
{
string myTextbox = Request.Form["txtBox1"] + "";
result.InnerHtml = "Result: " + myTextbox;
}

Related

C# Drop Down List Not Trigger index changing

I select one value on the ddl , and it does not show the products in the page. The selected value remains binded but the page is blank.
Also , if I just call function getCat() without using if(!ispostback). When i load the page the drop down list is stuck on the first value , but it shows the products in page.
Drop Down List:
<asp:dropdownlist runat="server" id="ddcateg" AutoPostBack="true" onselectedindexchanged="Ddcateg_SelectedIndexChanged"></asp:dropdownlist>
This is the implementation:
protected void Page_Load(object sender, EventArgs e)
{
//afisare();
if (!IsPostBack)
{
getCateg();
}
}
public void getCateg()
{
ProdusTipModel model = new ProdusTipModel();
FarmacieEntities db = new FarmacieEntities();
var lizt = (from c in db.ProdusTips select c).ToList();
ddcateg.DataSource = lizt;
ddcateg.DataValueField = "ID";
ddcateg.DataTextField = "Name";
ddcateg.DataBind();
ddcateg.SelectedIndexChanged += Ddcateg_SelectedIndexChanged;
}
public void afisare2(List<Produ> z)
{
ProdusModel mdl = new ProdusModel();
foreach (var produs in z)
{
Panel produsePnl = new Panel();
ImageButton imageButton = new ImageButton();
produsePnl.BorderColor = Color.AliceBlue;
Label lblNume = new Label();
Label lblPret = new Label();
produsePnl.BorderStyle = BorderStyle.Groove;
produsePnl.BorderColor = Color.LightSkyBlue;
imageButton.ImageUrl = "~/Img/Produse/" + produs.Image;
imageButton.CssClass = "imgProdus";
imageButton.PostBackUrl = "~/Pages/PaginaProdus.aspx?id=" + produs.ID;
lblNume.Text = produs.Name;
lblNume.CssClass = "numeProd";
lblPret.Text = produs.Price + "lei";
lblPret.CssClass = "produsPret";
produsePnl.Controls.Add(imageButton);
produsePnl.Controls.Add(new Literal { Text = "<br /" });
produsePnl.Controls.Add(lblNume);
produsePnl.Controls.Add(new Literal { Text = "<br /" });
produsePnl.Controls.Add(lblPret);
pnlProduse.Controls.Add(produsePnl);
}
}
private void Ddcateg_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList selectedList = (DropDownList)sender;
int selectedLit = Convert.ToInt32(selectedList.SelectedValue);
ProdusModel mdl = new ProdusModel();
List<Produ> list = mdl.GetProdCateg(selectedLit).ToList();
afisare2(list);
}
Your problem could be that your code behind method is private:
private void Ddcateg_SelectedIndexChanged(object sender, EventArgs e)
Try making it protected or public so it can be seen by the aspx page.

asp.net add link button dynamically click function

I'm trying to add a LinkButton dynamically
This is the html code:
<div id="resultDivText" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
</div>
This is the c# code
LinkButton lb = new LinkButton();
lb.Text = songName + "</br>"; //LinkButton Text
lb.ID = song.Key.ToString(); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(song.Key);
lb.CommandName = Convert.ToString(song.Key);
lb.Click += new EventHandler(test_Click);
this.form1.Controls.Add(lb);
PlaceHolder1.Controls.Add(lb);
And this is the "test_Click" function
protected void test_Click(object sender, EventArgs e)
{
showAllSong("let it be");
}
When i run the code it's show me the linkButton list but when i click on it nothing happens.
Try this code ..
static bool enable = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DynamicButton();
}
else if (enable)
{
DynamicButton();
}
}
protected void btnBindMapping_Click(object sender, EventArgs e)
{
enable = true;
DynamicButton();
}
protected void DynamicButton()
{
LinkButton lb = new LinkButton();
lb = new LinkButton();
lb.Text = songName + "</br>"; //LinkButton Text
lb.ID = song.Key.ToString(); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(song.Key);
lb.CommandName = Convert.ToString(song.Key);
lb.Click += new EventHandler(test_Click);
this.form1.Controls.Add(lb);
PlaceHolder1.Controls.Add(lb);
}
protected void test_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('done'); </script>");
}
You code is fine ..it works as expected ..But change this line
this.form1.Controls.Add(lb);
to
this.Controls.Add(lb);
Note:It postback to your server not a client sided event
Since you use CommandName and CommandArgument in the LinkButton, you have to delegate a Command not a Click.
lb.Command += new CommandEventHandler(test_Click);
protected void test_Click(object sender, CommandEventArgs e)
{
Response.Write(e.CommandArgument + "<br>" + e.CommandName);
}
And remove the line this.form1.Controls.Add(lb);
And this is not clear from your question, but you have to create that button every time the page is loaded, and that includes a PostBack.
In give detail you have not mention. when this dynamic button is created.
Because that may create a issue.
If you call your c# code in page load event then it works.
LinkButton lb = new LinkButton();
lb = new LinkButton();
lb.Text = songName + "</br>"; //LinkButton Text
lb.ID = song.Key.ToString(); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(song.Key);
lb.CommandName = Convert.ToString(song.Key);
lb.Click += new EventHandler(test_Click);
this.form1.Controls.Add(lb);
PlaceHolder1.Controls.Add(lb);
if that button create dynamically on oninit or onload event then it works.

Passing Class as an argument to an image click event Handler

I have a Trip object which I am getting from list TripsByTripIds which I want to pass as a parameter to image click event handler down below. how do I pass it?
foreach (Tripclass Trip in TripsByTripIds )
{
ImageButton imageButton = new ImageButton();
imageButton.ImageUrl = "~/" +Trip.CorridorName+"/"+Trip.Time+"/"+Trip.ImgFileName;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
AMSPanel1.Controls.Add(imageButton);
AMSPanel1.Height = Unit.Pixel(860);
}
protected void imageButton_Click(object sender, ImageClickEventArgs fi)
{
testimage.ImageUrl = ((ImageButton)sender).ImageUrl;
lblTime.Text = Trip.Time;
lblLocation.Text = Trip.Location; //can't access trip object here
}
I found answer from one of posts in stack overflow the other day.i haven't saved that link though. but the solution below solves my problem
foreach (Tripclass Trip in TripsByTripIds )
{
ImageButton imageButton = new ImageButton();
imageButton.ImageUrl = "~/" + Trip.CorridorName + "/" + Trip.Time + "/" + Trip.ImgFileName;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler((a, b) => imageButton_Click(a, b,Trip));
AMSPanel1.Controls.Add(imageButton);
AMSPanel1.Height = Unit.Pixel(860);
}
protected void imageButton_Click(object sender, ImageClickEventArgs e, Tripclass Trip)
{
testimage.ImageUrl = ((ImageButton)sender).ImageUrl;
lblTime.Text = Trip.Time;
lblLocation.Text = Trip.Location; //I can access trip object here
}
If it can be represented as text, you can add your value to CommandArgument property

dynamic imagebutton click event not getting fired

dynamic imagebutton click event not getting fired please help
i have created dynamic buttons in the asp.net oninit method
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ImageButton img = new ImageButton();
img.ID = "first_button";
img.Click += new ImageClickEventHandler(first_Click);
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ClassLibrary1.image.first.gif");
img.Attributes.Add("onmouseover", "onmousehand(this,'over')");
img.Attributes.Add("onmouseout", "onmousehand(this,'out')");
p1.Controls.Add(img);
img.Dispose();
img = new ImageButton();
img.ID = "previous_button";
img.Click += new ImageClickEventHandler(previous_Click);
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ClassLibrary1.image.previous.gif");
img.Attributes.Add("onmouseover", "onmousehand(this,'over')");
img.Attributes.Add("onmouseout", "onmousehand(this,'out')");
p1.Controls.Add(img);
img.Dispose();
t1.Attributes.Add("style", "color:#666666;");
// t1.Text = "Page " + current_page + " of " + total_pages;
t1.ID = "text_box1";
t1.Attributes.Add("onclick", "textbox_enable('" + t1.ClientID + "')");
p1.Controls.Add(t1);
img = new ImageButton();
img.ID = "go_button";
img.Click += new ImageClickEventHandler(go_Click);
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ClassLibrary1.image.go.GIF");
img.Attributes.Add("onmouseover", "onmousehand(this,'over')");
img.Attributes.Add("onmouseout", "onmousehand(this,'out')");
p1.Controls.Add(img);
img.Dispose();
ImageButton img1 = new ImageButton();
img1.ID = "next_button";
img1.CommandName = "next_button";
img1.CommandArgument = "next1";
img1.Click += new ImageClickEventHandler(next_Click);
img1.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ClassLibrary1.image.next.gif");
img1.Attributes.Add("onmouseover", "onmousehand(this,'over')");
img1.Attributes.Add("onmouseout", "onmousehand(this,'out')");
p1.Controls.Add(img1);
//img.Dispose();
img = new ImageButton();
img.ID = "last_button";
img.Click += new ImageClickEventHandler(last_Click);
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ClassLibrary1.image.last.gif");
img.Attributes.Add("onmouseover", "onmousehand(this,'over')");
img.Attributes.Add("onmouseout", "onmousehand(this,'out')");
p1.Controls.Add(img);
img.Dispose();
}
private void next_Click(object sender, ImageClickEventArgs e)
{
ImageButton next = (ImageButton)sender;
string value = next.CommandArgument;
current_page++;
t1.Text = "Page " + current_page + "of" + total_pages;
}
protected override void Render(HtmlTextWriter writer)
{
t1.Text = "Page " + current_page + " of " + total_pages;
p1.RenderControl(writer);
base.Render(writer);
}
Try this
protected void Page_Load(object sender, EventArgs e)
{
ImageButton img = new ImageButton();
img.ID = "SampleImage";
img.Click += new ImageClickEventHandler(img_Click);
this.form1.Controls.Add(img);
}
void img_Click(object sender, ImageClickEventArgs e)
{
Response.Write("Hello World");
}
You can define your dynamic buttons functionality in Page_Init instead of Oninit.
protected void Page_Init(object sender, EventArgs e)
{
ImageButton imagebutton = new ImageButton();
imagebutton.ID = "myID";
imagebutton.Attributes.Add("runat", "server");
imagebutton.Click += new ImageClickEventHandler(image_Click);
this.form1.Controls.Add(imagebutton);
}
void image_Click(object sender, ImageClickEventArgs e)
{
//Your code here
}

Trouble using findcontrol to find values from dynamic Literal Control

I'm having problems with finding my controls in my dynamically created literal control. I want to be able to grab the value in the label with the fnameID(x) id.
ASPX:
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(new LiteralControl("<Label id='fnameID"
+ i + "' >test" + i + "</Label><br/>"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label lbl = (Label)Panel1.FindControl("fnameID0");
Response.Write(lbl.Text);
}
Currently I am getting the following error when I click on the button:
Object reference not set to an instance of an object.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
{
Label lbl = (Label)Page.FindControl("fnameID0");
**Response.Write(lbl.Text);**
}
Try explicitly setting the ID of the control you generate:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
LiteralControl dynLabel = new LiteralControl("<Label id='fnameID"
+ i + "' >test" + i + "</Label><br/>");
dynLabel.ID = "fnameID" + i.ToString();
Panel1.Controls.Add(dynLabel);
}
}
You're getting the null reference exception because no control with the specified ID is being found, so FindControl is returning null, and you can't get the Text property of a null.

Categories