我们一般对大量的数据是通过数据集,将结果赋给DataGrid,而对于SqlDataReader的结果呢,我试将结果先一行一行的插入到表中,再将表赋个其数据源:下面是一个例子:
SqlConnection conn=new SqlConnection();
conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"];
string sqlStatement="select * from Orders where CustomerID=@ID order by OrderID";
SqlCommand sqlcmd=new SqlCommand(sqlStatement,conn);
sqlcmd.Parameters.Add("@ID",CustomerID);
conn.Open();
conn.ConnectionString=ConfigurationSettings.AppSettings["ConnectionString"];
string sqlStatement="select * from Orders where CustomerID=@ID order by OrderID";
SqlCommand sqlcmd=new SqlCommand(sqlStatement,conn);
sqlcmd.Parameters.Add("@ID",CustomerID);
conn.Open();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(sqlcmd);
da.Fill(ds,"Table");
this.dg.DataSource=ds;
this.textBox1.DataBindings.Add("Text",ds,"Table.CustomerID");
try
{
SqlDataReader sdr=sqlcmd.ExecuteReader();
int cols=sdr.FieldCount;
DataTable Mytab=new DataTable();
Mytab.BeginLoadData();
for(int i=0;i<cols;i++)
{
Mytab.Columns.Add(sdr.GetName(i),sdr.GetType());
}
string [] lvitem=new string[cols];
object [] values=new object[cols];
while(sdr.Read())
{
DataRow myRow=Mytab.NewRow();
Mytab.BeginLoadData();
for(int i=0;i<cols;i++)
{
Mytab.Columns.Add(sdr.GetName(i),sdr.GetType());
}
string [] lvitem=new string[cols];
object [] values=new object[cols];
while(sdr.Read())
{
DataRow myRow=Mytab.NewRow();
sdr.GetValues(values);
for(int i=0;i<values.Length;i++)
myRow[i]=values[i].ToString();
Mytab.Rows.Add(myRow);
}
for(int i=0;i<values.Length;i++)
myRow[i]=values[i].ToString();
Mytab.Rows.Add(myRow);
}
Mytab.EndLoadData();
this.dg.DataSource=Mytab;
sdr.Close();
}
catch(System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
//Another Way
this.dg.DataSource=Mytab;
sdr.Close();
}
catch(System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
//Another Way
CommonCS为一个类库文件名:
public class CommonCS
{
public CommonCS()
{
}
//add by guoyong 06-07-06
//静态方法的好处就是不用去声明即可调用
public static SqlConnection mycon()
{
SqlConnection con = new SqlConnection("server=.;database=bookstore;uid=sa;pwd=sa");
return con;
}
}
在绑定页面里加如下代码:
SqlConnection con=CommonCS.mycon();
con.Open();
SqlCommand cmd = new SqlCommand("select * from VoteDetails",con);
SqlDataReader sdr= cmd.ExecuteReader();
dgVoteResult.DataSource=sdr;
dgVoteResult.DataBind();