消息错误“没有行可以添加到没有列的DataGridView控件。必须先添加列。”

时间:2016-05-05 16:43:10

标签: c#

我尝试使用包含的(行)和HEADERS(列)填充datagridview,但对我来说这个错误:

  

没有行可以添加到没有列的DataGridView控件。必须先添加列。

数据源:SQL服务器 真的我累了试试请帮助我,先谢谢..

1 个答案:

答案 0 :(得分:0)

以下是一些示例代码。

string sqlQuery = "SELECT * from Customer";
                string cs = ConfigurationManager.ConnectionStrings["OLEDB"].ConnectionString;

                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand(sqlQuery, con);
                    con.Open();
                    gvResultsDeal.DataSource = cmd.ExecuteReader();
                    gvResultsDeal.DataBind();

                }

然后,您需要在SQL语句中调用以下FOR EVERY COLUMN。

<asp:GridView ID="gvResultsDeal" runat="server" AutoGenerateColumns="False" CssClass="table table-striped" OnSelectedIndexChanged="gvResultsDeal_SelectedIndexChanged" ShowHeader="False">
                <Columns>
                    <asp:BoundField DataField="CUST" HeaderText="Opportunity ID" SortExpression="CUST" >
                    <ItemStyle Width="160px" />
                    </asp:BoundField>
                    <asp:BoundField DataField="ADDRESS" HeaderText="DRA Instance" SortExpression="ADDRESS" >
                    <ItemStyle Width="36px" />
                    </asp:BoundField>

                </Columns>
            </asp:GridView>