在GridView中添加按钮后,如何触发按钮的各种事件?
1.在GridView的“編輯列”屬性窗口中,增加新的Botton列。
2.然后再該窗口右邊屬性中,將外觀項下的ButtonType設(shè)置一下,設(shè)置項有:如:Link、Button、Image。
3.屬性設(shè)置完成后,在右邊屬性列表窗口的下方有這樣一行超鏈接藍(lán)字:“將此字段轉(zhuǎn)換為TemplateField”,單擊這個超鏈接,把該列插入進(jìn)來的字段轉(zhuǎn)換為模版。
//添加了一個刪除控件,并將其轉(zhuǎn)換為模版后的代碼,該控件還和在GridView所在行的主鍵進(jìn)行綁定,把主鍵作為參數(shù)帶到該控件的各個事件函數(shù)中。
<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.??然后即可在編輯模版狀態(tài)下,編輯、設(shè)置這個控件的各種事件了,比如雙擊這個控件按鈕,系統(tǒng)則會自動在.cs文件中添加該控件的OnClick事件觸發(fā)的函數(shù)。
注意:如果你的GridView中加入了多個轉(zhuǎn)換為模版的列,進(jìn)入編輯模版狀態(tài)后,要選擇相應(yīng)的轉(zhuǎn)換為模版的列,才能進(jìn)行編輯。如下圖:
另:在cs文件中調(diào)用Gridview中按鈕綁定的值:
?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????}
做網(wǎng)站的時候 會出現(xiàn)很多的不同的問題,很多書上又找不到,對于GridView的應(yīng)用書上學(xué)來終覺淺呀!
網(wǎng)上找了很多,也試了很多方法 終于找到了簡單的語句。在這里分享下,希望幫到大家。
自定義操作獲取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中設(shè)置隱藏列并獲取隱藏列的值
網(wǎng)上大多是設(shè)置DataKeyNames來實(shí)現(xiàn),還可以用模板來實(shí)現(xiàn):
?
asp:TemplateField HeaderText=" " Visible="false"> //模板列設(shè)置成不可見。
?????<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的值。
?
?
?
簡單易明的實(shí)現(xiàn)效果,這篇就這樣了。
總結(jié)
以上是生活随笔為你收集整理的在GridView中添加按钮后,如何触发按钮的各种事件?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linkbutton控件中使用Comma
- 下一篇: JSP GridView --使用自定义