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中按鈕綁定的值:
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 }