Reputation: 3896
I have a gridview that is populated with data from SQL and I would like to add buttons/linkbuttons dynamically to its columns.
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button button = new Button();
button.ID = "row" + e.Row.RowIndex;
button.Text = "click me";
button.Click += new EventHandler(Unnamed_Click);
e.Row.Cells[1].Controls.Add(button);
}
Visually that works fine but when clicking it, it does a postback and the changes are lost. The buttons are gone.
Where can I recreate them so they persist?
Upvotes: 0
Views: 1444
Reputation: 447
Please use the below steps to bypass the binding of grid in case the click me button was clicked
Change your OnRowBound function code to:
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex != -1)
{
Button button = new Button();
button.ID = "gridview1row" + e.Row.RowIndex;
button.UseSubmitBehavior = false;
button.Text = "click me";
button.Click += new EventHandler(Unnamed_Click);
e.Row.Cells[1].Controls.Add(button);
}
}
Add the below check to you Page_Load before Grid View Load
protected void Page_Load(object sender, EventArgs e)
{
try
{
if ( Request.Params["__EventTarget"] == null || !Request.Params["__EventTarget"].Contains("gridview1row"))
{
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (SqlCommand command =
new SqlCommand("SELECT TOP 100 * FROM dbo.TableName", connection))
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = command;
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
}
catch (Exception ex)
{
}
}
Upvotes: 0
Reputation: 761
You can use command field or template field for buttons, below is example for image button:
<asp:CommandField ShowEditButton="true" EditImageUrl="~/images/edit.png" ButtonType="Image" ItemStyle-Width="20px" HeaderStyle-Width="20px" AccessibleHeaderText="Edit">
<HeaderStyle Width="20px" />
<ItemStyle Width="20px" />
</asp:CommandField>
Or
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit"
ImageUrl="~/images/edit.png" ToolTip="Click to Edit></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
Upvotes: 1