//在GridView中添加按鈕後,如何觸發按鈕的各種事件?
1.在GridView的“編輯列”屬性視窗中,增加新的Botton列。
2.然後再該視窗右邊屬性中,将外觀項下的ButtonType設定一下,設定項有:如:Link、Button、Image。
3.屬性設定完成後,在右邊屬性清單視窗的下方有這樣一行超連結藍字:“将此字段轉換為TemplateField”,單擊這個超連結,把該列插入進來的字段轉換為模版。
//添加了一個删除控件,并将其轉換為模版後的代碼,該控件還和在GridView所在行的主鍵進行綁定,把主鍵作為參數帶到該控件的各個事件函數中。
<asp:TemplateField ShowHeader="False" HeaderText="删除">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandArgument='<%# Eval("ClientID") %>'
OnClick="LinkButton1_Click" Text="删除"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
//這是一個沒有綁定字段值的新增Button列,将其裝換為模版後的代碼如下:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" CausesValidation="false" CommandName="" Text="按鈕" OnClick="Button2_Click" />
</ItemTemplate>
</asp:TemplateField>
4. 然後即可在編輯模版狀态下,編輯、設定這個控件的各種事件了,比如輕按兩下這個控件按鈕,系統則會自動在.cs檔案中添加該控件的OnClick事件觸發的函數。
注意:如果你的GridView中加入了多個轉換為模版的列,進入編輯模版狀态後,要選擇相應的轉換為模版的列,才能進行編輯。如下圖:

另:在cs檔案中調用Gridview中按鈕綁定的值:
1
protected void LinkButton2_Click( object sender, EventArgs e)
2
{
3
SqlConnection myconn;
4
SqlCommand mycommand;
5
myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["BaseConnectionString"].ConnectionString);
6
string sql = "update Bbs_Message set ISTOP=1 where Bbs_MessageIS=" + ((LinkButton)sender).CommandArgument.ToString();
7
//Response.Write(sql);
8
myconn.Open();
9
mycommand = new SqlCommand(sql, myconn);
10
mycommand.ExecuteNonQuery();
11
myconn.Close();
12
13
Response.Redirect("SQS_ADD3.aspx?XkzSqsID=" + Request.QueryString["XkzSqsID"].ToString());
14
}
做網站的時候 會出現很多的不同的問題,很多書上又找不到,對于GridView的應用書上學來終覺淺呀!
網上找了很多,也試了很多方法 終于找到了簡單的語句。在這裡分享下,希望幫到大家。
自定義操作擷取GridView行的索引:
例:在GridView模闆中添加Button,單擊Button的時候希望擷取該操作行row,
protected void Button1_Click(object sender, EventArgs e)
{
int row = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
//擷取該操作行中的其他控件 因為不可直接引用.
LinkButton lnk = (LinkButton)gv.Rows[row].FindControl("LinkButton1");
……//其他語句
}
GridView中設定隐藏列并擷取隐藏列的值
網上大多是設定DataKeyNames來實作,還可以用模闆來實作:
asp:TemplateField HeaderText=" " Visible="false"> //模闆列設定成不可見。
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# eval_r("字段名") %>' />
</ItemTemplate>
</asp:TemplateField>
Im擷取還是用:
Label lbl = (Label)gv.Rows[row].FindControl("Label1");
string text=lbl.Text;//即為Lable1的值。
簡單易明的實作效果,這篇就這樣了。