在填充datagridview的第二个循环中引发异常 [英] Throwing exception with the second loop in filling datagridview

查看:140
本文介绍了在填充datagridview的第二个循环中引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好
我在winform应用程序上工作,想用datatable的特定列填充datagridview并添加一个名为条形码项的列.第一列用于物料编号,第二列填充由物料编号生成的条形码,第三列用于物料名称.第一个循环运行良好,但是在第二个循环中,当填充datagridviw中的第二行时,它将引发异常.这是代码

那么问题和解决方案是什么

我尝试过的事情:

hi every body
i work on winform application and want to fill a datagridview with specific columns of datatable and add a column named barcode item. the first column is for item no, the second column is filled with barcode generated from Item no and the third column is for item name. the first loop running good, but with the second loop it throwing exception when fill the second row in datagridviw. here is the code

so what is the problem and the solution

What I have tried:

try
     {
             SqlCommand cmdss1 = new SqlCommand("usp_Get_All_Item", cn);
             cmdss1.CommandType = CommandType.StoredProcedure;



             cmdss1.Parameters.Clear();



             SqlDataAdapter SQss1 = new SqlDataAdapter(cmdss1);
             DataTable dtss1 = new DataTable();
             SQss1.Fill(dtss1);
             if (dtss1.Rows.Count > 0)
             {

                 for (int i = 0; i <= dtss1.Rows.Count - 1; i++)
                 {


                     string ssqs1 = dtss1.Rows[i]["Item_No"].ToString();
                     string ssqs2 = dtss1.Rows[i]["Item_Name"].ToString();

                     string s = ssqs1;


                     Image m1 = BarcodeLib.Barcode.DoEncode(BarcodeLib.TYPE.CODE39, s, true, Color.Black, Color.White, 1200, 1200);

                     dataGridView1.Rows[i].Cells[0].Value = ssqs1;
                     dataGridView1.Rows[i].Cells[1].Value = m1;
                     dataGridView1.Rows[i].Cells[2].Value = ssqs2;



                 }



             }
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.ToString());
     }

推荐答案

您似乎没有在datagridview中添加任何行:因此,当您尝试设置值时,几乎可以肯定行和行数已用完.结果是例外.使用索引不会创建新行-您必须使用DataGridView.Rows.Add方法显式地执行该操作.
You don;t appear to add any rows to your datagridview: so when you try to set values you are almost certainly running out of rows and an exception is the result. Useing an index does not create a new row - you have to do that explicitly with the DataGridView.Rows.Add method.


这篇关于在填充datagridview的第二个循环中引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆