【发布时间】:2013-01-09 03:52:59
【问题描述】:
我一直在尝试关注这个答案:How to implement full row selecting in GridView without select button?
但我还是有点困惑。在关注了那个问题之后,我的行现在可以点击了。但是我如何在被点击后实现它来做某事呢?目前,我使用一个按钮来对每行数据库执行我需要的操作:
这是 .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 不是很熟悉,所以我真的不知道失败的地方以及添加数据库逻辑需要做什么。
谢谢
【问题讨论】:
-
具体是哪一行抛出异常?什么样的异常?请注意,您应该使用
as LinkButton而不是as Button,因为SelectRow是LinkButton。 -
天哪!现在我把它变成了一个链接按钮,现在没有错误了。你知道我应该在哪里输入数据库代码的逻辑(例如,单击这一行并对数据库执行此操作)吗?现在,当我单击它时,什么也没有发生,因为我不确定在哪里/如何添加代码。谢谢!
-
处理 GridView 的 RowCommand 事件。