I have a gridview in an aspx page with c# code behind.
Is there a way how i can run a code behind function when the user clicks anyw开发者_C百科here on a row? For now, i use the select button. But then the user has to click on that button. And i want to user to be able to click anywhere on a row to show it's details in another gridview that is located next to the main gridview.
Some ideas here on how to do this?
Thanks!
try this
<asp:GridView runat="server" ID="GridView1" DataKeyNames="ID" AutoGenerateColumns="False"
Font-Names="Tahoma" Font-Size="Small" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:CommandField ShowSelectButton="true" ButtonType="Link" Visible="false" SelectText="Enroll" />
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = Enumerable.Range(1, 10).Select(a => new
{
ID = a,
FirstName = String.Format("First {0}", a),
LastName = String.Format("Last{0}", a)
});
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//Bind other grid
Response.Write(GridView1.SelectedIndex+1);
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//add css to GridViewrow based on rowState
e.Row.CssClass = e.Row.RowState.ToString();
//Add onclick attribute to select row.
e.Row.Attributes.Add("onclick", String.Format("javascript:__doPostBack('GridView1','Select${0}')", e.Row.RowIndex));
}
}
精彩评论