【问题标题】:How to get different text for each button in same column dynamically in datagridview如何在datagridview中动态获取同一列中每个按钮的不同文本
【发布时间】:2018-10-10 08:13:14
【问题描述】:

我创建了一个具有 datagridview 的用户控件。然后我从 datagridview 的文本文件中动态添加了行和列。

我的问题是我需要每行都有按钮的列。第一行按钮的文字是“Test1”,第二行的“Test2”不是同一个文字。

在谷歌上搜索后我尝试了这个代码

var testButton = new DataGridViewButtonColumn();
testButton.Name = "Test";
testButton.HeaderText = "Test";
testButton.UseColumnTextForButtonValue = true;

testButton.Text = "Test1";
this.dataGridView1.Columns.Add(testButton);

但它给了我两个按钮文本为“Test1”。

【问题讨论】:

标签: c# winforms button datagridview ado.net


【解决方案1】:

假设您在 Windows 窗体中,您需要将 DataGridViewButtonColumn 添加到您的 DataGridView - 而不是直接添加到 DataTable

这应该发生在您将DataTable 绑定到DataGridView 之后的某个地方。

这样的事情应该可以工作:

DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "uninstall_column";
uninstallButtonColumn.Text = "Uninstall";
int columnIndex = 2;
if (dataGridViewSoftware.Columns["uninstall_column"] == null)
{
    dataGridViewSoftware.Columns.Insert(columnIndex, uninstallButtonColumn);
}

当然,您必须处理网格的CellClick 事件才能对按钮执行任何操作。

在你的 DataGridView 初始化代码中添加这个

dataGridViewSoftware.CellClick += dataGridViewSoftware_CellClick;

然后创建处理程序:

private void dataGridViewSoftware_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == dataGridViewSoftware.Columns["uninstall_column"].Index)
    {
        //Do something with your button.
    }
}

【讨论】:

    【解决方案2】:
    //Change the Button text property on a data-bound event 
    
        protected void YourDataGridViewId_RowDataBound(object sender, GridViewRowEventArgs e)
        {
           // finding the button control..`enter code here`.
    
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               Button YourbtnVariable = (Button)e.Row.FindControl("YourbuttonID");
               YourbtnVariable.Text = "Text"+e.Row.RowIndex+1;
               //e.Row.RowIndex+1 will give u index of row every time incremented with 1
            }
    
        }
    

    【讨论】:

    • 请对您的代码进行一些解释,以便大家更好地理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2013-06-04
    • 2021-01-01
    • 2013-06-14
    • 2015-08-13
    • 2015-11-04
    相关资源
    最近更新 更多