I created a dynamic button inside c# code and I have assigned some value in button.text but the problem is that on buttn_Click event I want to show details related to that value. So any idea how to do this?
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < list.Count; i++)
{
lnk1 = new Button();
VW obj1 = list[i];
lnk1.Text = " "+obj1.ticketNo+": "+obj1.subject+": "+obj1.qu;
lnk1.Click += new EventHandler(lnk1_Click);
}
}
I want to show above mentioned obj1.ticketno in next page like ticket No: some value is selected
You could retrieve the reference to the button using the sender parameter of the event handler and cast the value to the Button type.
In lnk1_Click event handler you can get the link by type casting the sender to Button type and get the link text. Using that you can retrieve ticket number for which click has been done.
Something like this:
void lnk1_Click(object sender)
{
Button clickedLinkButton = sender as Button;
String buttonText = clickedLinkButton .Text;
String clickedTicketNumber =
buttonText
.SubString(0, buttonText.IndexOf(':'))
.Trim();"
}
Here is the sample code segment
protected void lnk1_Click(object sender, EventArgs e)
{
Button bt = sender as Button;
bt.Text;
}
you can use GridView or Repeater and in Iteme Template you can put button. and bind perticular grid or repeater.
<asp:repeater runat="server" id="rpt">
</ItemTemplate>
<asp:LinkButton runat="serevr" ID="lbtnLInkButton" CommandArgument='<%#Eval("ID") %>' CommandName="Edit" OnClick="lbtnLInkButton_Click">"+<%#Eval("ticketNo")%> <%#Eval("subject")%> <%#Eval("qu")%>
</ItemTemplate>
</asp:repeater>
Bind This Repeater to Datatable or make Dummy DataTable and bind it.
DataTable dt = new DataTable();
dt.Columns.Add("ticketNo");
dt.Columns.Add("Subject");
dt.Columns.Add("qu");
for (int i = 0; i < list.Count; i++)
{
dt.Rows.Add(new object[] { "Ticket Number Value", "Subject Value", "qu Value"});
}
rpt.DataSource = dt;
rpt.DAtabind();
You can get button event like this
protected void lbtnLInkButton_Click(object sender, EventArgs e)
{
int i = Convert.ToInt32(((LinkButton)sender).CommandArgument);
}
***Note : I have writtern the code extempore and not rested it on Visual Studio so there May be Some Spelling Mistakes.**
Related
Using grid view binding it from code behind:
I want to bind a particular column data into a hyper link so when it clicked it should do a download.
How to do that ?
Below is my code :
for (int i = 0; i <= tbl.Columns.Count - 1; i++)
{
Telerik.Web.UI.GridBoundColumn boundfield = new Telerik.Web.UI.GridBoundColumn();
if (tbl.Columns[i].ColumnName.ToString() == "Row")
{
LinkButton lkbtn = new LinkButton();
lkbtn.CommandName = i;
lkbtn.CommandArgument = "dwnld";
lkbtn.Font.Underline = true;
lkbtn.Text = tbl.Columns(i).ColumnName.ToString();
boundfield.DataField = tbl.Columns(i).ColumnName.ToString()
boundfield.HeaderText = tbl.Columns(i).ColumnName.ToString();
GridView2.MasterTableView.Columns.Add(boundfield);
}
}
Why not use grid template column with link button.
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnDownload" OnClick="btnDownload_Click" runat="server">Download Something</asp:LinkButton>
</ItemTemplate>
</telerik:GridTemplateColumn>
protected void btnDownload_Click(object sender, EventArgs e)
{
LinkButton lbBtn = sender as LinkButton;
GridDataItem item = (GridDataItem)(sender as LinkButton).NamingContainer;
// Use item to get other details
...
...
}
I have some questions to this post [1]: How can i create dynamic button click event on dynamic button?
The solution is not working for me, I created dynamically an Button, which is inside in an asp:table controller.
I have try to save my dynamic elements in an Session, and allocate the Session value to the object in the Page_Load, but this is not working.
Some ideas
edit:
...
Button button = new Button();
button.ID = "BtnTag";
button.Text = "Tag generieren";
button.Click += button_TagGenerieren;
tabellenZelle.Controls.Add(button);
Session["table"] = table;
}
public void button_TagGenerieren(object sender, EventArgs e)
{
TableRowCollection tabellenZeilen = qvTabelle.Rows;
for (int i = 0; i < tabellenZeilen.Count; i++)
{
...
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["table"] != null)
{
table = (Table) Session["table"];
Session["table"] = null;
}
}
}
It is not a good practice to store every control into Session state.
Only problem I found is you need to reload the controls with same Id, when the page is posted back to server. Otherwise, those controls will be null.
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Label runat="server" ID="Label1"/>
protected void Page_Load(object sender, EventArgs e)
{
LoadControls();
}
private void LoadControls()
{
var button = new Button {ID = "BtnTag", Text = "Tag generieren"};
button.Click += button_Click;
PlaceHolder1.Controls.Add(button);
}
private void button_Click(object sender, EventArgs e)
{
Label1.Text = "BtnTag button is clicked";
}
Note: If you do not know the button's id (which is generated dynamically at run time), you want to save those ids in ViewState like this - https://stackoverflow.com/a/14449305/296861
The problem lies in the moment at which te button and it's event are created in the pagelifecycle. Try the page_init event for this.
Create Button in page load
Button btn = new Button();
btn.Text = "Dynamic";
btn.Click += new EventHandler(btnClick);
PlaceHolder1.Controls.Add(btn)
Button Click Event
protected void btnClick(object sender, EventArgs e)
{
// Coding to click event
}
I have a custom grid on which i have binded data in my c# code behind. I have given a hyperlink field to one of my column. If i click the hyperlink value, it should navigate to the details page of that hyperlink value. The code is given below,
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink myLink = new HyperLink();
myLink.Text = e.Row.Cells[2].Text;
e.Row.Cells[2].Controls.Add(myLink);
myLink.NavigateUrl = "Estimation.aspx?EstimateID=" + EstimateID + "&VersionNo=" + VersionNo;
}
}
If i click the link, the page is getting navigated, but i am not getting the details which are already pre-loaded in that page. Please give me suggestions on how to incorporate this.
Thanks
You can use this to redirect, read this
<asp:HyperLink ID="HyperLink1"
runat="server"
NavigateUrl="Default2.aspx">
HyperLink
</asp:HyperLink>
to add attribute with link just add
HyperLink1.Attributes.Add ("");
You need to do a small change in the RowDataBound event
myLink.Attributes.Add("href"," your url");
You need to fetch the values for EstimateID and VersionNo from the grid row data. Take a look at the documentation for GridViewRowEventArgs and you'll see there's a .Row property.
So your code needs to be something like:
myLink.NavigateUrl = "Estimation.aspx?EstimateID=" + e.Row.Cells[4].Text + "&VersionNo=" + e.Row.Cells[5].Text;
Or, maybe you need to get to the data item associated with the grid row, in which case take a look at e.Row.DataItem, the GridViewRow.DataItem property. This DataItem will need to be cast to the type of data you've bound to the grid in order to fetch the data from it, which might be something like:
((MyCustomDataRow)e.Row.DataItem).EstimateID
Try below solution :
Page-1 that is your list page :
ASPX code :
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind :
protected void Page_Load(object sender, EventArgs e)
{
List<Data> lstData = new List<Data>();
for (int index = 0; index < 10; index++)
{
Data objData = new Data();
objData.EstimateID = index;
objData.VersionNo = "VersionNo" + index;
lstData.Add(objData);
}
GridView1.DataSource = lstData;
GridView1.DataBind();
}
public class Data
{
public int EstimateID { get; set; }
public string VersionNo { get; set; }
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink HyperLink1 = e.Row.FindControl("HyperLink1") as HyperLink;
HyperLink1.NavigateUrl = "Details.aspx?EstimateID=" + e.Row.Cells[1].Text + "&VersionNo=" + e.Row.Cells[2].Text;
}
}
Page-2 that is your details page :
Code behind :
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.QueryString["EstimateID"].ToString());
Response.Write(Request.QueryString["VersionNo"].ToString());
}
I want to find an item in the datalist on page load method this is my code
protected void Page_Load(object sender, EventArgs e)
{
//some code here
for (int i = 0; i < count ; i++)
{
LinkButton LinkButton6 = (LinkButton)sender;
DataListItem item = (DataListItem)LinkButton6.NamingContainer;
LinkButton lnkbtn6 = (LinkButton)DataList1.Items[item.ItemIndex].FindControl("LinkButton6");
}
}
but this error appears to me :Unable to cast object of type 'ASP.default2_aspx' to type 'System.Web.UI.WebControls.LinkButton'.
Page_Load is not an event triggered by LinkButton so sender cannot be a LinkButton. It is a Page event. Use OnItemDataBound instead
Markup
<asp:DataList OnItemDataBound="DataList1_OnItemDataBound" runat="server" ID="MdataList">
<ItemTemplate>
<asp:LinkButton runat="server" ID="LinkButton6" Text="Text"></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
Codebehind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DataList1_OnItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkBtn6 = (LinkButton)e.Item.FindControl("LinkButton6");
lnkBtn6.Text = "Some Text Here";
}
On this line:
LinkButton LinkButton6 = (LinkButton)sender;
the sender object is the Page, not LinkButton, isn't it?
I have a webpage where I have a gridview. I have populated the gridview on page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadGridView();
}
}
This is the load gridview method.
private void loadGridView()
{
dataTable dt = getData(); // this function populates the data table fine.
gridView1.dataSource = dt;
gridview1.dataBind();
}
Now I have added linkButtons in one of the gridview columns in the RowDataBound event of the grid view.
protected void gvTicketStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lb = new LinkButton();
lb.Text = str1; // some text I am setting here
lb.ID = str2; // some text I am setting here
lb.Click += new EventHandler(lbStatus_click);
e.Row.Cells[3].Controls.Add(lb);
}
Finally This is the event Handler code for the link button click event.
private void lbStatus_click(object sender, EventArgs e)
{
string str = ((Control)sender).ID;
// next do something with this string
}
The problem is, the LinkButtons appear in the data grid fine, but the click event does not get execute. the control never reaches the event handler code. when I click the link button, the page simply gets refreshed. What could be the problem?
I have tried calling the loadGridView() method from outside the (!isPostBack) scope, but it did not help!
Try to work with the "Command" property instead of Click event
LinkButton lnkStatus = new LinkButton();
lnkStatus.ID = string.Format("lnkStatus_{0}", value);
lnkStatus.Text = "some text here";
lnkStatus.CommandArgument = "value";
lnkStatus.CommandName = "COMMANDNAME";
lnkStatus.Command += new CommandEventHandler(lnkStatus_Command);
Otherwise, if my proposal doesn't satisfy you, you have to remove the !Postback on Page_Load event.
you have to use OnRowCommand event of the GridView.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("LinkButton1")) //call the CommandArgument name here.
{
//code
}
}