2014-01-24 35 views
1

我在每一行上都有一個GridViewImageButton。我想通過單擊按鈕從模板字段獲取值。我在button_click中使用了SelectedIndexGridView的選定索引在按鈕單擊上的值爲-1

SelectedIndex總是-1。

我試過的代碼如下。

protected void ImageButton1_Click(object sender, ImageClickEventArgs e) 
    { 
     int i = GridView1.SelectedIndex; 
     Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1"); 
     Session["course"] = t.Text; 
     Response.Redirect("registration.aspx"); 
    } 
+0

單擊該按鈕不一定選擇該行。看看如何添加圖像,以及如何在點擊圖像按鈕時強制選擇該行。 – Kangkan

+0

我已經使用圖像按鈕作爲gridview中的模板字段。 – user3065219

回答

0

你不會在ButtonClick事件得到的SelectedIndex

所以嘗試這樣

protected void imgbtn_Click(object sender, EventArgs e) 
{ 
    try { 
     // Get the button that raised the event 
     LinkButton lnkbtn = (LinkButton)sender; 
     // Get the row that contains this button 
     GridViewRow gvRow = (GridViewRow)lnkbtn.NamingContainer; 
     // Get rowindex 
     int i = gvRow.RowIndex; 
     Label t = (Label)GridView1.Rows[i].Cells[0].FindControl("Label1"); 
     Session["course"] = t.Text; 
     Response.Redirect("registration.aspx"); 
     } 
    } catch (Exception ex) { 

    } 
} 

protected void grdview1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    try { 
     if ((e.CommandName == "ImageButton")) { 
      // Get RowIndex 
      int RowIndex = Convert.ToInt32(e.CommandArgument); 
      // Get Row 
      GridViewRow gvr = grdPhone.Rows(RowIndex); 
     } 
    } catch (Exception ex) 
     { 

    } 
} 

ASPX:

在GridView的

你需要設置的CommandName和論證像此

<asp:TemplateField ShowHeader="false"> 
<ItemTemplate> 
    <asp:ImageButton ID="imgbtn" runat="server" OnClick="imgbtn_Click" CausesValidation="false" CommandName="ImageButton" CommandArgument='<%# Container.DataItemIndex %>'>Edit</asp:ImageButton > 
    </ItemTemplate> 
    </asp:TemplateField> 
+0

我不認爲點擊將在網格視圖中工作,以及爲什麼當您可以在onRowcommand中編寫所有邏輯時需要點擊。 – Raghurocks

+0

CLick將在網格視圖中工作 –

相關問題