繁体   English   中英

如何将选定的行从sql数据库加载到C#中的DataGridView?

[英]How to load selected rows from sql database to DataGridView in C#?

我需要将所选数据显示到我的DataGridView中,该数据根据组合框中的所选PO_No而定。所以我尝试了此方法,但是对于所选PO_No只显示了一行

public void loadPOCarttable()
    {
        DynamicConnection con = new DynamicConnection();

        try
        {
            con.sqlquery("select b.BookName,b.ISBN_No,p.OrderQuantity,p.UnitPrice,p.Total from TBL_Book b, TBL_PO_Cart p where b.ISBN_No=p.ISBN_No and PO_No='" + cmbPO.Text + "'");
            con.mysqlconnection();
            con.datatable();
            con.dataread();
            //con.table.Load(con.datareader);
            int i = 0;
            while (con.datareader.Read())
            {
                dataGridView1.Rows[i].Cells[0].Value = con.datareader["BookName"].ToString();
                dataGridView1.Rows[i].Cells[1].Value = con.datareader["ISBN_No"].ToString();
                dataGridView1.Rows[i].Cells[2].Value = con.datareader["OrderQuantity"].ToString();
                dataGridView1.Rows[i].Cells[3].Value = con.datareader["UnitPrice"].ToString();
                dataGridView1.Rows[i].Cells[4].Value = con.datareader["Total"].ToString();
                i++;
            }
            //this.dataGridView1.DataSource = con.table;

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error Occured" + ex.Message);
        }
    }

并显示此错误。如何解决此问题,请在此处输入图片说明

首先,请确保您已具备所有单元格的需求,然后尝试如下操作:

while (con.datareader.Read())
{
    DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
    row.Cells[0].Value = con.datareader["BookName"].ToString();
    row.Cells[1].Value = con.datareader["ISBN_No"].ToString();
    row.Cells[2].Value = con.datareader["OrderQuantity"].ToString();
    row.Cells[3].Value = con.datareader["UnitPrice"].ToString();
    row.Cells[4].Value = con.datareader["Total"].ToString();
    dataGridView1.Rows.Add(row);
}

更新资料

使用this.dataGridView1.Rows.Clear(); 清除以前的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM