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
Related
I am creating dynamic textboxes when clicking on a set of different radio button. Below is an example of two radio button onclick event.
protected void Checkbox1_CheckedChanged(object sender, EventArgs e)
{
string servicename = "service1";
if (checkbox1.Checked)
{
InputParameters.InputParameters aa= new InputParameters.InputParameters();
textbox = aa.GetInputFields(servicename);
for (int i=0;i<textbox.Count;i++)
{
// declare a textbox
TextBox CPDT = new TextBox();
CPDT.ID = servicename + i.ToString();
CPDT.CssClass = "form-control";
CPDT.EnableViewState = true;
Label lblCPD=new Label();
lblCPD.ID = "txtDynamiclbl" + servicename+ i.ToString();
lblCPD.CssClass= "form-control-label";
lblCPD.Text= textbox[i].ToString();
lblCPD.EnableViewState = true;
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
//this.NumberOfControls++;
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
else
{
}
}
protected void Checkbox2_CheckedChanged(object sender, EventArgs e)
{
string servicename = "service2";
if (checkbox2.Checked)
{
InputParameters.InputParameters aa = new InputParameters.InputParameters();
List<String> textbox = aa.GetInputFields("test1");
// textboxs.AddRange(textbox);
for (int i = 0; i < textbox.Count; i++)
{
// declare a textbox
TextBox CPDT = new TextBox();
CPDT.ID = servicename + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + servicename + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
}
Button callSoap = new Button();
callSoap.ID = "txtDynamicSearch" + servicename;
callSoap.Text = "Search";
callSoap.CssClass = ".btn-info";
callSoap.CommandArgument = "test1";
callSoap.Click += new EventHandler(btnsoap);
callSoap.EnableViewState = true;
CPDPlaceHolder.Controls.Add(callSoap);
}
else
{
}
}
The textboxes and search button appears as needed. The problem now is when i clicked on the search button a post back occur and all the controls are gone. I have been reading a lot about initialising the controls in page_preinit and i tried the code below.
protected void Page_PreInit(object sender, EventArgs e)
{
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
int i = 1;
try
{
foreach (string key in keys)
{
TextBox CPDT = new TextBox();
CPDT.ID = "test" + i.ToString();
CPDT.CssClass = "form-control";
Label lblCPD = new Label();
lblCPD.ID = "txtDynamiclbl" + "test" + i.ToString();
lblCPD.CssClass = "form-control-label";
lblCPD.Text = textbox[i].ToString();
CPDPlaceHolder.Controls.Add(lblCPD);
CPDPlaceHolder.Controls.Add(CPDT);
i++;
}
}
catch
{
}
}
In the above function this line only returns the search button and not the texboxes. I am stuck on this issue.
List<string> keys = Request.Form.AllKeys.Where(key => key.Contains("txtDynamic")).ToList();
T
I use Ajax toolkit.I want create text editor for HTML codes. I found .css file in html link tags and for each of these files, create a LinkButton. I want when user click linkbutton .css file open in editor. I write this code:
string textHtml = "";
List<string> listTextHtml = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
AsyncPostBackTrigger d = new AsyncPostBackTrigger();
if (IsPostBack)
return;
StreamReader re = new StreamReader(string.Concat(Server.MapPath("/"), "\\Engine\\TextFile1.txt"));
while (re.Peek() > 0)
{
txtHtmlCode.Content = txtHtmlCode.Content + re.ReadLine() + "\n";
}
textHtml = txtHtmlCode.Content;
re.Close();
string temp = textHtml;
while (temp.Contains("link"))
{
string s = temp.Substring(temp.IndexOf("link"), temp.IndexOf("/>"));
temp = temp.Substring(temp.IndexOf("/>") + 2);
if (s.IndexOf(".css") >= 0)
{
s = s.Substring(s.IndexOf("href=\"") + 6);
listTextHtml.Add(s.Substring(0, s.IndexOf("\"") - 1));
}
//temp = temp.Substring(temp.IndexOf("href="));
//temp = temp.Substring(temp.IndexOf("\"") + 1);
//listTextHtml.Add(temp.Substring(0, temp.IndexOf("\"") - 1));
//temp = temp.Substring(temp.IndexOf("\"") + 1);
}
int i = 0;
hfString.Value = "";
foreach (var item in listTextHtml)
{
//HtmlGenericControl li = new HtmlGenericControl("li");
LinkButton lb = new LinkButton();
lb.ID = i.ToString();
lb.Text = "Link - " + i.ToString();
//lb.Click += ltnCssLoad_Click;
lb.Click += new EventHandler(this.ltnCssLoad_Click);
//li.Controls.Add(lb);
phTags.Controls.Add(lb);
d.ControlID = i.ToString();
d.EventName = "Click";
//udpMain.Triggers.Add(d);
i++;
hfString.Value += item + "|";
}
}
when click the linkbutton this function must run:
protected void ltnCssLoad_Click(object sender, EventArgs e)
{
LinkButton ClickedLink = (LinkButton)sender;
string[] listText = hfString.Value.Split('|');//string.Concat(Server.MapPath("/"),
StreamReader re = new StreamReader(string.Concat(string.Concat(Server.MapPath("/"), listText[int.Parse(ClickedLink.ID)])));
txtHtmlCode.Content = "";
while (re.Peek() > 0)
{
txtHtmlCode.Content = txtHtmlCode.Content + re.ReadLine() + "\n";
}
re.Close();
}
but when I use break point in function ltnCssLoad_Click, this function not work when I click in linkbutton. How can I fix this?
This is not working because when you click link button or any dynamically added control it causes post back and you have "return"ed in page load event handler if IsPostBack is true.
The pain with using dynamic controls is that you have to recreate them every time (first request as well as subsequent post backs).
Restrict file reading to first request (i.e. put it in !IsPostBack condition) and let link buttons' creation code run after that.
I have to display n grids, n is variable, then I dont know how many grids I'll have.
My problem is, I have to init this grids with Visible false and when click in a button show the grid specific for that button, then how can I link a button to a gridview?
My code that generate the grids:
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view"+i;
grv.Visible = false;
grv.DataSource = dt;
grv.DataBind();
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br /><br />";
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["DESC_OCORRENCIA"].ToString();
tipoOcorrencia = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tipoOcorrencia);
int quantidade = lst.Count;
lblTipo.Text = tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button"+i;
lkBtn.Text = "+";
place_grids.Controls.Add(lblBlankLines);
place_grids.Controls.Add(lkBtn);
place_grids.Controls.Add(lblTipo);
place_grids.Controls.Add(grv);
place_grids.DataBind();
i++;
}
Thanks in advance.
Modify your foreach loop as below.
private void GenerateControls()
{
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view" + i;
//grv.Visible = false;//Commented as the grid needs be generated on client side, in order to make it visible from JavaScript/jQuery
grv.Attributes.Add("style", "display:none;");
grv.DataSource = dt;
grv.DataBind();
//Adding dynamic link button
LinkButton lnkButton = new LinkButton();
lnkButton.Text = "button " + i;
//lnkButton.Click += new EventHandler(lnkButton_Click);
lnkButton.ID = "lnkButton" + i;
lnkButton.OnClientClick = "ShowGrid('" + grv.ClientID + "');";
Label lblTipo = new Label();
lblTipo.Text = "text " + i;
lblTipo.ID = "lbl" + i;
tempPanel.Controls.Add(lblTipo);
tempPanel.Controls.Add(grv);
tempPanel.Controls.Add(lnkButton);
tempPanel.DataBind();
i++;
}
}
Then you will have to add a link button click event as below, if you want server side event to fire. (Un-comment the line where event handler is assigned to link button.)
protected void lnkButton_Click(Object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
String index = lnkButton.ID.Substring(lnkButton.ID.Length - 1);
GridView grv = (GridView)tempPanel.FindControl("grid_view" + index);
grv.Visible = true;
}
You will need to add all dynamically added controls in the Page_Init event for maintaining their state. Refer below links can be useful.
Dynamically Created Controls losing data after postback
ViewState in Dynamic Control
Call method GenerateControls from Page_Init event as below.
protected void Page_Init(object sender, EventArgs e)
{
GenerateControls();
}
EDIT :
JavaScript function...
function ShowGrid(gridID) {
document.getElementById(gridID).style.display = ''
}
I have kept the server side click event as it is. But I have commented the line where the event handler is assigned to the link button.
Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.
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
}