且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在基于C#Windows的项目中在运行时添加行和列

更新时间:2023-12-06 15:10:22

这取决于您用来显示数据的内容.
如果您使用的是DataGridView,则它将提供您将需要的所有功能: ^ ]



谢谢您的回复.但是我正在使用包含文本框的控件.我正在运行时在其中添加内容.因此,在这种情况下,我如何添加列和行.请回复".

对不起?我是否理解正确,您正在尝试添加文本框的行和列?如果是这样,那为什么呢?为什么让自己的生活变得艰难?
您可以做到-只需使用
创建它们
It depends on what you are using to display the data.
If you are using a DataGridView, then it will provide all the facilities you will need: MSDN[^]



"Thanks for Reply. But I am using controls which includes textboxes. I am adding at them at run time. so In that case how can I add columns and row. Please reply"

Sorry? Do I understand you right that you are trying to add rows and columns of textboxes? If so, then why? Why make life difficult for yourself?
You can do it - just create them using
TextBox tb = new TextBox();

设置位置"和大小"属性,并将它们添加到控件"列表中:

Set the Location and Size properties, and add them to the forms Controls list:

for (int i = 0; i < 5; i++)
   {
   TextBox tb = new TextBox();
   tb.Size = new Size(100, 25);
   tb.Location = new Point(25, 25 + (i * 30));
   Controls.Add(tb);
   }



但这是一种笨拙,低效且难以维护的方法.
为什么不使用为完全满足您的需要而构建的控件:提供单元格的行和列... DataGridView.从长远来看,它将为您省去很多麻烦...



But it''s a clumsy, inefficient, and hard-to-maintain way to do it.
Why not use a control that is built to do exactly what you need: provide rows and columns of cells...the DataGridView. It will save you a lot of hassle in the long run...


您好,lovejaygore您的问题不清楚.
通过使用datagridview,我们可以添加列和行,听到的是示例代码.

hi lovejaygore your question was not clear.
by using datagridview we can add columns and rows, hear is the sample code.

private void dataGridView2_RowsAdded(object sender,DataGridViewRowsAddedEventArgs e)
   {

     for (int i = 1; i < e.RowCount; i++)
    this.dataGridView2.Rows[e.RowIndex + i].Cells[0].Value =(e.RowIndex+i).ToString();



    }


如果有帮助,我感到很高兴...


i feel happy if it helps...


希望以下代码对您有用!
您可以使用方法addrowsandcolumns添加n个行和列.

快乐的编码:)

Hope the below code is useful for you!
You can add n number of rows and columns using the method addrowsandcolumns.

Happy coding:)

DataTable dtSource;
private DataTable addrowsandcolumns(int nRow,int ncolumn)
{
    dtSource = new DataTable();
    for (int i = 0; i < ncolumn; i++)
    {
        dtSource.Columns.Add(i.ToString());
    }

    for (int i = 0; i < nRow; i++)
    {
        for (int j = 0; j < ncolumn; j++)
        {
            DataRow dr = dtSource.NewRow();
            dr[j] = "";
            dtSource.Rows.Add(dr);
        }
    }

    return dtSource;
}

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.DataSource = addrowsandcolumns(3, 5);
}