我一直努力遵循这样的回答:How to implement full row selecting in GridView without select button?制作中的GridView整行可点击
但我还是略显混乱。在遵循这个问题之后,我的行现在可以点击了。但是我怎么实现它来点击后做点什么?目前,我用一个按钮做什么,我需要每行数据库:
下面是在.aspx代码:
<Columns>
<asp:ButtonField Text = "Click Me" CommandName = "Clicked" ButtonType = "Button" />
...other columns stuff
</Columns>
C#代码背后:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
//if button is clicked
if (e.CommandName == "Clicked")
{
//go find the index on the gridview
int selectedIndex = MsgInbox.SelectedIndex;
if (int.TryParse(e.CommandArgument.ToString(), out selectedIndex))
{
//do something with database
}
现在,精美的作品。但是,我不希望按钮是可点击的,我希望整行都是可点击的。我知道这是目前错误的,但是这是我到目前为止的代码:
的.aspx代码
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="SelectRow" runat="server" ForeColor="red" CommandName="Clicked"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C#代码:
protected void Gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
var selectButton = e.Row.FindControl("SelectRow") as Button;
e.Row.Attributes["onclick"] = ClientScript.GetPostBackEventReference(selectButton, "");
我得到一个简单的空指针异常当我这样做时,但我并不真正熟悉e.Row.Attributes,所以我真的不知道这是哪里失败,以及我需要做什么来添加数据库逻辑。
谢谢
哪一行特别是抛出一个异常?什么样的例外?注意你应该使用'作为LinkButton'而不是'作为Button',因为'SelectRow'是一个'LinkButton'。 –
哦,甜美!现在我没有错误,现在我做了一个LinkButton。你知道我应该在哪里输入数据库代码的逻辑(例如,单击这一行并对数据库执行此操作)?现在,当我点击它时,没有任何反应,因为我不确定在哪里/如何添加代码。谢谢! – Kevin
处理GridView的RowCommand事件。 –