//把数据放到DataTable中
DataTable c_dtDtTble = null;
public DataTable GetDataSet()
{
SqlConnection conn = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Contact1", conn);
ds = new DataSet();
adapter.Fill(ds, "Contact1");
c_dtDtTble=ds.Table[0];
return c_dtDtTble ;
}
//动态添加dataGridView列标题
private void Form1_Load(object sender, EventArgs e)
{
c_intColumnCount = c_dtDtTble1.Columns.Count;
for (int i = 0; i < c_intColumnCount; i++)
{
DataGridViewColumn l_dgvClmn = new DataGridViewTextBoxColumn();
l_dgvClmn.Name = c_dtDtTble1.Columns[i].ColumnName;
l_dgvClmn.HeaderText = c_dtDtTble1.Columns[i].ColumnName;
dgvContact2.Columns.Add(l_dgvClmn);
}
}
//填充单元格数据
private void dgvContact1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
e.Value = c_dtDtTble.Rows[e.RowIndex][e.ColumnIndex].ToString();
}