How to bind dataGridView predefined columns with columns from sql statement (without adding new columns)?

前端 未结 5 1337
萌比男神i
萌比男神i 2021-02-13 22:30

Is there a elegant way, to bind predefined dataGridView columns with results from a SQL statement?

Example:

dataGridView1.Columns.Add(\"EID\", \"ID\");
d         


        
相关标签:
5条回答
  • 2021-02-13 23:14

    How about adding columns to the Columns tag of your gridview like so?

    <Columns>
    <asp:BoundField DataField="EID" HeaderText="ID" />
    <asp:BoundField DataField="FName" HeaderText="First name" />
    ...
    
    0 讨论(0)
  • 2021-02-13 23:15

    If you are doing WinForm, the important part is setting the DataPropertyName property to match the DataTable Column name. You can do it in the designer or code as follows:

    Me.AccountDataGridView.Columns("Account").DataPropertyName = "Account"
    

    Of course, having set this:

    Me.AccountDataGridView.AutoGenerateColumns = False
    
    0 讨论(0)
  • 2021-02-13 23:19

    Aside from setting AutoGenerateColumns to false, you also need to set DataPropertyName for each column in the DataGridView to the corresponding field in the data source. You can set this in the designer or in code before setting the DataSource property.

    0 讨论(0)
  • 2021-02-13 23:24

    Use dataGridView1.Columns["FName"].DataPropertyName = "FName" where FName is column in your data table.

    0 讨论(0)
  • 2021-02-13 23:32

    I think the DataGridView has an AutoGenerateColumns property, doesn't it?

    dataGridView1.AutoGenerateColumns = True;
    

    From the MSDN docs:

    public bool AutoGenerateColumns { set; get; } Member of System.Windows.Forms.DataGridView

    Summary: Gets or sets a value indicating whether columns are created automatically when the System.Windows.Forms.DataGridView.DataSource or System.Windows.Forms.DataGridView.DataMember properties are set.

    Returns: true if the columns should be created automatically; otherwise, false. The default is true.

    The property isn't on the Properties window though, you have to set it via code as in my example.

    0 讨论(0)
提交回复
热议问题