日期:2014-05-18 浏览次数:21049 次
private void button1_Click(object sender, EventArgs e) { string conStr = "Data Source=.;Initial Catalog=db;User ID=sa;Password=sa"; SqlConnection Conn = new SqlConnection(conStr); Conn.Open(); var list = new List<int>(); SqlCommand cmd = new SqlCommand("select id, chengshi from chengshi where hide is null", Conn); SqlDataReader Reader = cmd.ExecuteReader(); while (Reader.Read()) { list.Add(Reader.GetInt32(0)); } Reader.Dispose(); cmd.Dispose(); foreach (var item in list) { var sql = "select id, quyu from quyu where chengshi_id=" + item.ToString() + " and hide is null"; SqlCommand cmd2 = new SqlCommand(sql, Conn); SqlDataReader red2 = cmd2.ExecuteReader(); // 提示这段有问题 while (red2.Read()) { textBox1.Text = red2.GetInt32(0).ToString(); Application.DoEvents(); } red2.Dispose(); cmd2.Dispose(); } Conn.Close(); }
------解决方案--------------------
定义个类,代码也稍作修改
private void button1_Click(object sender, EventArgs e) { string conStr = "Data Source=.;Initial Catalog=db;User ID=sa;Password=sa"; SqlConnection Conn = new SqlConnection(conStr); Conn.Open(); var list = new List<Tuple>(); SqlCommand cmd = new SqlCommand("select id, chengshi from chengshi where hide is null", Conn); SqlDataReader Reader = cmd.ExecuteReader(); while (Reader.Read()) { var tuple = new Tuple { id = Reader.GetInt32(0), quyu = Reader.GetString(1) }; list.Add(tuple); } Reader.Dispose(); cmd.Dispose(); foreach (var item in list) { var sql = "select id, quyu from quyu where chengshi_id=" + item.id.ToString() + " and hide is null"; SqlCommand cmd2 = new SqlCommand(sql, Conn); SqlDataReader red2 = cmd2.ExecuteReader(); // 提示这段有问题 while (red2.Read()) { textBox1.Text = red2.GetInt32(0).ToString(); Application.DoEvents(); } red2.Dispose(); cmd2.Dispose(); } Conn.Close(); } private class Tuple { public int id; public string quyu; }