2013-03-15 77 views
2

我有GridView,我在其中使用代碼添加BoundField。現在我想添加編輯按鈕和使用代碼刪除。我知道如何使用代碼將ButtonField添加到網格,但我想添加一個按鈕,因爲ButtonField沒有CommandArgument屬性。以編程方式向GridView添加按鈕

這裏是我的GridView標記:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CellPadding="4" 
       BorderWidth="1px" ForeColor="#333333" GridLines="None"> 
    <AlternatingRowStyle BackColor="White" /> 
    <FooterStyle BackColor="#990000" ForeColor="White" Font-Bold="True" /> 
    <HeaderStyle Height="30px" BackColor="#990000" Font-Bold="True" ForeColor="White" /> 
    <PagerStyle ForeColor="#333333" HorizontalAlign="Center" BackColor="#E2E2E2" /> 
    <RowStyle CssClass="test" BackColor="#E2E2E2" Height="25px" BorderWidth="1px" ForeColor="#333333" /> 
    <SelectedRowStyle BackColor="#E2E2E2" Font-Bold="True" ForeColor="Navy" /> 
    <SortedAscendingCellStyle BackColor="#FDF5AC" /> 
    <SortedAscendingHeaderStyle BackColor="#4D0000" /> 
    <SortedDescendingCellStyle BackColor="#FCF6C0" /> 
    <SortedDescendingHeaderStyle BackColor="#820000" /> 
</asp:GridView> 

這裏是我的C#代碼:

GridView1.DataKeyNames = new string[] { PrimaryKey }; 

if (dtOutPutResult.Rows.Count > 0) 
{ 
    foreach (DataColumn dcDtOutPutResult in dtOutPutResult.Columns) 
    { 
     foreach (DataRow drDtColumns in dtColumns.Rows) 
     { 
      if (drDtColumns["OrignalColumn"].ToString() == dcDtOutPutResult.ColumnName) 
      { 
       BoundField bfield = new BoundField(); 
       bfield.DataField = dcDtOutPutResult.ColumnName; 
       bfield.HeaderText = drDtColumns["DisplayColumn"].ToString(); 
       GridView1.Columns.Add(bfield); 
      } 
     } 
    } 

    foreach (DataRow dr in dtOutPutResult.Rows) 
    { 
     var buttonField = new ButtonField 
     { 
      ButtonType = ButtonType.Button, 
      Text = "My button", 
      CommandName = "DoSomething", 
     }; 
     GridView1.Columns.Add(buttonField); 
     break; 
    } 

    GridView1.DataSource = dtOutPutResult; 
    GridView1.DataBind(); 
    lblMessage.Visible = false; 
} 
else 
{ 
    GridView1.DataSource = dtOutPutResult; 
    GridView1.DataBind(); 
    lblMessage.Visible = true; 
    lblMessage.Style.Add("Color", "Red"); 
    lblMessage.Text = "No Record Found."; 
} 
+0

使用gridview RowDataBound方法。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx – DavidB 2013-03-15 10:23:52

+0

我不想使用,是否有任何其他方式,因爲我已經在代碼中使用 – 2013-03-15 10:24:36

+0

@DavidB除了使用網格事件,我們可以做到嗎? – 2013-03-15 10:25:08

回答

1

這聽起來像你想添加一個CommandField

CommandField cField = new CommandField(); 
cField.EditText = "Edit"; 
cField.DeleteText = "Delete"; 
cField.UpdateText = "Update"; 
cField.CancelText = "Cancel"; 

cField.ShowEditButton = true; 
cField.ShowDeleteButton = true; 

GridView1.Columns.Add(cField); 

這些按鈕將發送CommandArgument像你想要的,並應該觸發RowCommand事件(如果你想處理該事件)。

相關問題