用 DataSet.Tables[0].Rows.count 判断数据集是否有数据,防止出错

例:

 

代码
   
     
1 OleDbDataAdapter cn = new OleDbDataAdapter( " select xm,xb,sfzh,csny,mzmc,jtdz,ksh,lqzy,dept,jhxzmc,cj,lb,xscc from T_TDD where ksh = ' " + ksh2 + " ' " , con);
2 DataSet i = new DataSet();
3 con.Open();
4 cn.Fill(i);
5 con.Close();
6 if (i.Tables[ 0 ].Rows.Count > 0 )
7 {
8 string xm = i.Tables[ 0 ].Rows[ 0 ][ 0 ].ToString();
9 string xb = i.Tables[ 0 ].Rows[ 0 ][ 1 ].ToString();
10 string sfzh = i.Tables[ 0 ].Rows[ 0 ][ 2 ].ToString();
11 string csny = i.Tables[ 0 ].Rows[ 0 ][ 3 ].ToString();
12 string mz = i.Tables[ 0 ].Rows[ 0 ][ 4 ].ToString();
13 string jtdz = i.Tables[ 0 ].Rows[ 0 ][ 5 ].ToString();
14 string ksh = i.Tables[ 0 ].Rows[ 0 ][ 6 ].ToString();
15 string lqzy = i.Tables[ 0 ].Rows[ 0 ][ 7 ].ToString();
16 string dept = i.Tables[ 0 ].Rows[ 0 ][ 8 ].ToString();
17 string jhxzmc = i.Tables[ 0 ].Rows[ 0 ][ 9 ].ToString();
18 string cj = i.Tables[ 0 ].Rows[ 0 ][ 10 ].ToString();
19 string lb = i.Tables[ 0 ].Rows[ 0 ][ 11 ].ToString();
20 string xscc = i.Tables[ 0 ].Rows[ 0 ][ 12 ].ToString();
21
22 Label2.Text = xm;
23 Label3.Text = xb;
24 Label4.Text = sfzh;
25 Label5.Text = csny;
26 Label6.Text = mz;
27 Label7.Text = jtdz;
28 Label8.Text = ksh;
29 Label9.Text = lqzy;
30 Label10.Text = dept;
31 Label11.Text = jhxzmc;
32 Label12.Text = cj;
33 Label13.Text = lb;

    首先,第6行这里要用到 i.Tables[0].Rows.count > 0判断下有没有数据,如果大于0继续执行下面的数据获取,

如果条件不成立,提示数据库中无此数据。

    如果没有这个判断的话,会出现数据获取的时候无此行数据报错。

 

    供参考吧。

你可能感兴趣的:(table)