DataReader 填充 DataTable
1
try
2
{
3
SqlDataReader sdr=sqlcmd.ExecuteReader();
4
int cols=sdr.FieldCount;
5
DataTable Mytab=new DataTable();
6
Mytab.BeginLoadData();
7
for(int i=0;i<cols;i++)
8
{
9
Mytab.Columns.Add(sdr.GetName(i),sdr.GetType());
10
}
11
string [] lvitem=new string[cols];
12
object [] values=new object[cols];
13
while(sdr.Read())
14
{
15
DataRow myRow=Mytab.NewRow();
16
sdr.GetValues(values);
17
for(int i=0;i<values.Length;i++)
18
myRow[i]=values[i].ToString();
19
20
Mytab.Rows.Add(myRow);
21
}
22
Mytab.EndLoadData();
23
this.dg.DataSource=Mytab;
24
sdr.Close();
25
26
}
27
catch(System.Data.SqlClient.SqlException ex)
28
{
29
MessageBox.Show(ex.Message);
30
}
31![](/Images/OutliningIndicators/None.gif)
32![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
2
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
3
![](/Images/OutliningIndicators/InBlock.gif)
4
![](/Images/OutliningIndicators/InBlock.gif)
5
![](/Images/OutliningIndicators/InBlock.gif)
6
![](/Images/OutliningIndicators/InBlock.gif)
7
![](/Images/OutliningIndicators/InBlock.gif)
8
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
9
![](/Images/OutliningIndicators/InBlock.gif)
10
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
11
![](/Images/OutliningIndicators/InBlock.gif)
12
![](/Images/OutliningIndicators/InBlock.gif)
13
![](/Images/OutliningIndicators/InBlock.gif)
14
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
15
![](/Images/OutliningIndicators/InBlock.gif)
16
![](/Images/OutliningIndicators/InBlock.gif)
17
![](/Images/OutliningIndicators/InBlock.gif)
18
![](/Images/OutliningIndicators/InBlock.gif)
19
![](/Images/OutliningIndicators/InBlock.gif)
20
![](/Images/OutliningIndicators/InBlock.gif)
21
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
22
![](/Images/OutliningIndicators/InBlock.gif)
23
![](/Images/OutliningIndicators/InBlock.gif)
24
![](/Images/OutliningIndicators/InBlock.gif)
25
![](/Images/OutliningIndicators/InBlock.gif)
26
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
27
![](/Images/OutliningIndicators/None.gif)
28
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
29
![](/Images/OutliningIndicators/InBlock.gif)
30
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
31
![](/Images/OutliningIndicators/None.gif)
32
![](/Images/OutliningIndicators/None.gif)