简体   繁体   English

将值添加到 DataGridview 中的特定单元格

[英]Add Values to Specific cells in DataGridview

I have a select query which reads a number from a table and counts its occurrence and display it in a datagridview.我有一个 select 查询,它从表中读取一个数字并计算其出现次数并将其显示在 datagridview 中。 I have the following code but all it does it show me the last number and its count.我有以下代码,但它所做的一切都向我显示了最后一个数字及其计数。

For example the last number in the loop is 30, so it will show number 30 in the datagridview and along with its count lets say 10, what I want to do is to view all the numbers from 1-30 and its count and display it in the datagridview.例如,循环中的最后一个数字是 30,因此它将在 datagridview 中显示数字 30,连同它的计数让我们说 10,我想要做的是查看 1-30 的所有数字及其计数并显示它在数据网格视图中。

foreach (DataGridViewRow row in dataGridView8.Rows)
{
    if (!row.IsNewRow)
    {
        for (int nu = 1; nu < 70; nu++)
        {
            string query = "Select count(*) from [AllData] where [Num2]=@Num2 And [Cd_Name]=@Cd_Name ";                                                                                                              
            SqlCeCommand cmd1 = new SqlCeCommand(query, con1);
            cmd1.Parameters.AddWithValue("@Num2", nu);
            cmd1.Parameters.AddWithValue("@Cd_Name", ab);
            cnt = Convert.ToInt32(cmd1.ExecuteScalar());
            cmd1.ExecuteReader();                           
            row.Cells[2].Value = nu.ToString();
            row.Cells[3].Value = cnt.ToString();                           
        }
    }
}

Below is the how the datagridview looks like.下面是 datagridview 的样子。

 Col_1  Col_2
    70   0                              
    70   0                              
    70   0                              
    70   0                              
    70   0                              
    70   0                              
    70   0                              
    70   0                              
    70   0                              
    70   0                                                          

What I want to do is in column 1 display the number and in column 2 display the total count of the number from the db.我想要做的是在第 1 列中显示数字,在第 2 列中显示来自数据库的数字的总数。

Actually I am not aware of your table structure and data.其实我不知道你的表结构和数据。 As per my understanding据我了解

 string query = "Select count(*) from [AllData] where [Num2]=@Num2 And [Cd_Name]=@Cd_Name "; SqlCeCommand cmd1 = new SqlCeCommand(query, con1); cmd1.Parameters.AddWithValue("@Num2", nu); cmd1.Parameters.AddWithValue("@Cd_Name", ab); cnt = Convert.ToInt32(cmd1.ExecuteScalar()); var cnt = cmd1.ExecuteScalar(); foreach (DataGridViewRow row in dataGridView8.Rows) { if (.row.IsNewRow) { row.Cells[2].Value = nu;ToString(). row.Cells[3].Value = cnt;ToString(); } }

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

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