将列表绑定到DataGridView

时间:2014-04-03 12:20:15

标签: c# list datagridview bind

我有一个类的列表,我想在datagridview中显示它。

这是我的代码,但它没有显示列表:

public partial class Configuration : UserControl
{
    TestInfoClass liste = new TestInfoClass();

    public Configuration()
    {
        InitializeComponent();

        datagridview_Items.DataSource = liste;    // here not work, not show anything        
    }
}

主要形式:

public partial class MainForm : Form
{
   Configuration list_to_dgv = new Configuration();
   TestInfoClass testInfo = null;
   //code...
   Configuration list_to_dgv = new Configuration();
}

1 个答案:

答案 0 :(得分:0)

我不知道你的回归功能是什么?所以我自己就这样做了一个例子。 返回列表的函数应该是这样的:

 public DataSet ShowUsers()
    {
        DataSet op = new DataSet();
        SqlConnection objconnection = new SqlConnection(obj.strconnection());
        SqlCommand objcommand = new SqlCommand();
        DataSet objdataset = new DataSet();
        SqlDataAdapter objdataadapter = new SqlDataAdapter();
        objdataadapter.SelectCommand = objcommand;
        objdataadapter.SelectCommand.Connection = objconnection;
        objdataadapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        objdataadapter.SelectCommand.CommandText = "ShowUsers";
        objdataadapter.Fill(objdataset, "sheet");
        return objdataset;
    }

在你的表格中你应该有这样的事情:

 DGVShowLetter.DataSource = obj.ShowUsers();
 DGVShowLetter.DataMember = "sheet";

所以我认为你应该添加 DataMember ,因此它不起作用。

如果您的班级中有对象列表,则应将列表转换为如下表格:

List<string[]> list = new List<string[]>();
        list.Add(new string[] { "Column 1", "Column 2", "Column 3" });
        list.Add(new string[] { "Row 2", "Row 2" });
        list.Add(new string[] { "Row 3" });

        // Convert to DataTable.
        DataTable table = ConvertListToDataTable(list);
        dataGridView1.DataSource = table;

转换功能:

static DataTable ConvertListToDataTable(List<string[]> list)
    {
        // New table.
        DataTable table = new DataTable();

        // Get max columns.
        int columns = 0;
        foreach (var array in list)
        {
        if (array.Length > columns)
        {
            columns = array.Length;
        }
        }

        // Add columns.
        for (int i = 0; i < columns; i++)
        {
        table.Columns.Add();
        }

        // Add rows.
        foreach (var array in list)
        {
        table.Rows.Add(array);
        }

        return table;
    }