簡體   English   中英

將按鈕添加到Winforms DataGridView

[英]Adding a button to a Winforms DataGridView

有沒有辦法在C#中的Winforms DataGridView單元格中添加控件(例如按鈕)?

(我的目標是在網格的不同單元格中放置各種控件......)

DataGridViewButtonColumn是一個包含可單擊按鈕的提供列類型。 您可以將自己的控件添加到單元格:

http://msdn.microsoft.com/en-us/library/7tas5c80.aspx

請記住,它並不總是微不足道,但我看到有人將整個DataGridView放入一個單元格 - 看起來很奇怪。

還有其他提供的列:

DataGridViewButtonColumn
DataGridViewCheckBoxColumn
DataGridViewComboBoxColumn
DataGridViewImageColumn
DataGridViewLinkColumn
DataGridViewTextBoxColumn

您可以在Visual Studio中的設計器中的列編輯器中更改這些更改,或者將它們在代碼中添加到Columns集合中。

你可以這樣做....

有兩種方法可以做到這一點:

  • 1)。 將DataGridViewCell轉換為存在的某個單元格類型。 例如,將DataGridViewTextBoxCell轉換為DataGridViewComboBoxCell類型。
  • 2)。 創建一個控件並將其添加到DataGridView的控件集合中,設置其位置和大小以適合要作為主機的單元格。

請參閱下面的示例代碼,其中說明了這些技巧。

代碼片段

    private void Form5_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("name");
        for (int j = 0; j < 10; j++)
        {
            dt.Rows.Add("");
        }
        this.dataGridView1.DataSource = dt;
        this.dataGridView1.Columns[0].Width = 200;

        /*
         * First method : Convert to an existed cell type such ComboBox cell,etc
         */

        DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();
        ComboBoxCell.Items.AddRange(new string[] { "aaa","bbb","ccc" });
        this.dataGridView1[0, 0] = ComboBoxCell;
        this.dataGridView1[0, 0].Value = "bbb";

        DataGridViewTextBoxCell TextBoxCell = new DataGridViewTextBoxCell();
        this.dataGridView1[0, 1] = TextBoxCell;
        this.dataGridView1[0, 1].Value = "some text";

        DataGridViewCheckBoxCell CheckBoxCell = new DataGridViewCheckBoxCell();
        CheckBoxCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        this.dataGridView1[0, 2] = CheckBoxCell;
        this.dataGridView1[0, 2].Value = true;

        /*
         * Second method : Add control to the host in the cell
         */
        DateTimePicker dtp = new DateTimePicker();
        dtp.Value = DateTime.Now.AddDays(-10);
        //add DateTimePicker into the control collection of the DataGridView
        this.dataGridView1.Controls.Add(dtp);
        //set its location and size to fit the cell
        dtp.Location = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Location;
        dtp.Size = this.dataGridView1.GetCellDisplayRectangle(0, 3,true).Size;
    }

我會在設計器中添加它並創建一個模板字段。 在datagridview中輕松實現您想要的任何內容

<asp:DataGrid ID="somedatagrid" runat="server">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:Button ID="somebutton" runat="server" Text="some button" />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM