检查gridview是否有选定的项目

时间:2010-08-30 08:37:08

标签: c# asp.net

我有一个grideview和2个按钮。我只需要在gridview有选定项目时显示按钮。我的代码如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    btactivate.Visible = false;
    btdeactivate.Visible = false;
    //Show Activate and Deactivate Buttons only if an item in the gridview is selected
    if (GridView1.SelectedIndex != -1)
    {
        btactivate.Visible = true;
        btdeactivate.Visible = true;
    }
    else
    {
        btactivate.Visible = false;
        btdeactivate.Visible = false;
    }
}   

但我现在遇到的问题是,只有当我第二次选择gridview中的项目时,按钮才显示出来。我第一次选择时需要显示按钮。我已经尝试将所选索引更改为“-0”,但始终显示按钮(即使我没有选择某些内容)。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Col1");
        dt.Columns.Add("Col2");
        dt.Columns.Add("Col3");

        for (int i = 0; i < 20; i++)
        {
            DataRow dr = dt.NewRow();
            dr["Col1"] = string.Format("Row{0}Col1", i + 1);
            dr["Col2"] = string.Format("Row{0}Col2", i + 1);
            dr["Col3"] = string.Format("Row{0}Col3", i + 1);
            dt.Rows.Add(dr);
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();

        SetButtonState();
    }
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    SetButtonState();
}

private void SetButtonState()
{
    btactivate.Visible = GridView1.SelectedIndex > -1;
    btdeactivate.Visible = GridView1.SelectedIndex > -1;
}