【问题标题】:How to add buttons to datagridview cells not entire column如何将按钮添加到 datagridview 单元格而不是整个列
【发布时间】:2011-09-12 16:49:33
【问题描述】:

如何在数据网格视图中为一行中的单元格而不是整个列添加一个按钮?

【问题讨论】:

    标签: c# vb.net visual-studio


    【解决方案1】:

    我认为阿德里安的回答很接近。试试这样的。

    if ((string)table.Rows[0].Cells[0].Value == "I should be a button") {
       // you can add formatting or values to the button before assigning it here
       table.Rows[0].cells[0] = new DataGridViewButtonCell();
    }
    

    【讨论】:

      【解决方案2】:

      我认为如果在这里找到最好的答案: Hide gridview button。您需要做的就是在需要按钮的地方添加 DataGridViewButtonCell,在不需要的地方添加 DataGridViewTextBoxCell。该列必须是 DataGridViewButton 类型。

      【讨论】:

        【解决方案3】:

        在 SO 中看到这个类似的帖子,可能会有所帮助

        adding control to gridview

        如果赢得表格,请查看此 MSDN 帖子

        Column Types in the Windows Forms DataGridView Control

        或者这个代码项目帖子......虽然它给出了添加图像按钮的示例

        DataGridView Image Button Cell

        @tmax 在这种情况下,您可能可以将按钮创建代码放在GridView_RowCreated 事件中,如下所示

        void GridView_RowCreated(Object sender, GridViewRowEventArgs e)
          {   
             if(e.Row.RowType == DataControlRowType.Header)
              {   
                   //Button creation code here        
              } 
          }
        

        【讨论】:

        • 从我在链接中看到的内容,它显示整个列具有相同的类型。我只想将按钮添加到第一行。
        【解决方案4】:
        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Button btn = new Button();
            //btn attributes
            dataGridView1.Rows[0].Cells[3].Value = new Button();
        }
        

        试试这样的。

        【讨论】:

        • 当然,...Cells[x]...你知道列号。
        • 抱歉,这也没用。单元格中的结果是“System.Windows.Forms.Button,文本:”。我很确定您必须将整个列设置为 Button DataType。我希望有一个替代方案,但还没有成功。
        • 你是对的,它不是这样工作的。如果您没有太大的应用程序,请尝试将其移植到 WPF。对不起。
        【解决方案5】:

        我最终做的是将一个 DataGridView 堆叠在另一个之上。我关闭了边框、网格线和滚动条。然后创建动态按钮列以仅与一行按钮匹配主datagridview。然后我使用 ColumnWidthChanged 事件处理程序一起调整两个 DataGridViews 的大小。无论如何,这是我现在的解决方法。

        【讨论】:

          【解决方案6】:
           DataGridViewButtonColumn dataGridViewButtonColumn = new DataGridViewButtonColumn();
                  dataGridViewButtonColumn.Name = "Select";
                  dataGridViewButtonColumn.HeaderText = "Select";
            
                  dataGridViewButtonColumn.ReadOnly = false;
                  dataGridView1.Columns.Add(dataGridViewButtonColumn);
          

          【讨论】:

            【解决方案7】:

            我不确定这是否会有所帮助,但您也可以考虑使用 TableLayoutPanel。

            参考:Winforms TableLayoutPanel adding rows programmatically

            【讨论】:

              猜你喜欢
              • 2010-09-22
              • 1970-01-01
              • 2016-03-30
              • 2014-02-07
              • 1970-01-01
              • 1970-01-01
              • 2015-04-10
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多