C# 如何将行添加到 datagridview winforms?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15965043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:37:33  来源:igfitidea点击:

How to add rows to datagridview winforms?

c#winformsdatagridview

提问by Viva

I want to add rows to a datagridview. I tried a lot of possibilities, but it doesn't appear anything on it. I think the best solution is to create a datatable, and then to use it as datasource for my gridview. I use winforms. Please, any other idea is welcomed . This is what I have tried so far:

我想将行添加到datagridview. 我尝试了很多可能性,但它没有出现任何内容。我认为最好的解决方案是创建一个数据表,然后将其用作我的 gridview 的数据源。我使用winforms。拜托,欢迎任何其他想法。这是我迄今为止尝试过的:

public DataTable GetResultsTable()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Name".ToString());
        table.Columns.Add("Color".ToString());
        DataRow dr;
        dr = table.NewRow();
        dr["Name"] = "Mike";
        dr["Color "] = "blue";
        table.AcceptChanges();
        return table;
    }
public void gridview()
{
     datagridview1.DataSource=null;
     datagridview1.DataSource=table;
}

采纳答案by Arshad

i found two mistake in your code:

我在你的代码中发现了两个错误:

  1. dr["Color "] = "blue";Column Color should without space dr["Color"] = "blue";
  2. You forgot to add row to the table

    table.Rows.Add(dr);

  1. dr["Color "] = "blue";列颜色应该没有空格 dr["Color"] = "blue";
  2. 您忘记向表中添加行

    table.Rows.Add(dr);

you can try this

你可以试试这个

public DataTable GetResultsTable()
{
    DataTable table = new DataTable();
    table.Columns.Add("Name".ToString());
    table.Columns.Add("Color".ToString());
    DataRow dr = table.NewRow();
    dr["Name"] = "Mike";
    dr["Color"] = "blue";
    table.Rows.Add(dr);
    return table;
}
public void gridview()
{          
    datagridview1.DataSource =  GetResultsTable();
}

回答by Freelancer

There are different ways , but in different conditions.

有不同的方式,但在不同的条件下。

As my following code shows you gridview.add method in case of string array:

正如我的以下代码在字符串数组的情况下向您展示了 gridview.add 方法:

datagridview1.Rows.Add( { val, val, val });

It depends upon context and situation at which you want to apply it.

这取决于您要应用它的上下文和情况。

回答by user2141886

DataGridView dgv = new DataGridView();

DataTable table = new DataTable();

dgv.DataSource = table;

table.Columns.Add("Name");
table.Columns.Add("Color");
table.Rows.Add("Mike", "blue");
table.Rows.Add("Pat", "yellow");

this.Controls.Add(dgv);

回答by Praveen VR

Try This method:

试试这个方法:

dataGridView1.Columns.Add("Col1", "Name"); // "Col1" is the name of the column and  "Name" is the column header text"
dataGridView1.Columns.Add("Col2", "Age");
dataGridView1.Rows.Add("ABC", "25");

Hope this helps :)

希望这可以帮助 :)