2010-08-30 57 views
0

我有一個grideview和2個按鈕。當gridview有一個選定的項目時,我只需要顯示按鈕。我的代碼如下所示:檢查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」,但始終顯示按鈕(即使我沒有選擇某些東西)。任何人都可以幫忙嗎?

回答

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; 
} 
+0

謝謝,這個工作! – CSharpSuzie 2010-08-30 11:20:07

相關問題