简体   繁体   中英

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. 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.

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.

 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.

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(); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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