在GridView列上创建超链接?

时间:2016-06-23 19:11:17

标签: c# asp.net gridview

我有一个名为“Keys”的列的GridView。如何使列Key's中的所有值都具有调用另一个函数(c#)的超链接,并且仍然保留与之前相同的名称。

我应该提到GridView根据没有用户输入设置了数据,它没有硬编码到网站。根据用户输入的内容,它会运行sql存储过程,并相应地更新GridView

我的数据绑定示例。

private void parseData(string command)
{
using (SqlConnection connection = new SqlConnection(strConnString))
        {
            SqlCommand instruc = new SqlCommand(command, connection);
            connection.Open();
            SqlDataAdapter myDA = new SqlDataAdapter();
            DataSet table = new DataSet();
            myDA.SelectCommand = instruc;
            myDA.Fill(table);
            dataTest.DataSource = table;
            dataTest.DataBind();
        }

}

GridView ASP代码:

<asp:GridView ID="dataTest" runat="server" AllowSorting="True" OnRowDataBound="gv_RowDataBound" OnSelectedIndexChanging="gv_SelectedIndexChanging">
        </asp:GridView>

1 个答案:

答案 0 :(得分:0)

您必须订阅

  

RowDataBoundEvent

在这种情况下,您可以创建链接按钮。

  

SelectedIndexChangingEvent   在这种情况下,您可以调用任何您喜欢的C#函数。

这样的事情应该有效:

<asp:GridView ID="gv" runat="server" OnRowDataBound="gv_RowDataBound" OnSelectedIndexChanging="gv_SelectedIndexChanging"></asp:GridView>

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var gv = sender as GridView;
        var dr = e.Row.DataItem as DataRow;
        var value = dr["Keys"] as string;
        var lb = new LinkButton();
        lb.CommandName = "Select";
        lb.Command += Lb_Command;
        lb.Text = value;
    }
}

private void Lb_Command(object sender, CommandEventArgs e)
{
    if (e.CommandName == "Select")
    {
        var lb = sender as LinkButton;
        var row = lb.Parent.Parent as GridViewRow; // can be parent depends lb.Parent.Parent...
    }
}

protected void gv_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
    // event fired after Linkbutton click
}