首页 > 代码库 > C# DataTable的用法

C# DataTable的用法

建表
DataTable dtP = new DataTable("Man");
加列
DataColumn dcP;
dcP =
new DataColumn("Name",Type.GetType("System.String"));
dcP.ReadOnly =
false;
dcP.AllowDBNull = false;
dcP.Unique =
true;
dtP.Columns.Add(dcP);
dcP = new DataColumn("Sexy",
Type.GetType("System.Int32"));
dcP.ReadOnly = false;
dcP.AllowDBNull =
false;
dcP.Unique = false;
dtP.Columns.Add(dcP);
dcP = new
DataColumn("Briday", Type.GetType("System.DateTime"));
dcP.ReadOnly =
false;
dcP.AllowDBNull = false;
dcP.Unique =
false;
dtP.Columns.Add(dcP);
加主键
DataColumn[] PK = new
DataColumn[1];
PK[0] = dtP.Columns["Name"];
dtP.PrimaryKey =
PK;
新建行
DataRow newRow;
newRow = dtP.NewRow();
newRow["Name"] =
textBox1.Text;
newRow["Sexy"] = checkBox1.Checked ? 1 :
0;
newRow["Briday"] =
Convert.ToDateTime(dateTimePicker2.Text);
dtP.Rows.Add(newRow);
dtP.AcceptChanges();
邦定DateGridView
dataGridView1.DataSource
=
dtP;
删除行
dtP.Rows[dataGridView1.CurrentRow.Index].Delete();
dtP.AcceptChanges();
更新行
int
dvIndex = dataGridView1.CurrentRow.Index;
string filterStr = "Name=‘" +
dataGridView1.Rows[dvIndex].Cells[0].Value.ToString() + "‘";
string tmpName =
null;
string tmpSexy = null;
string tmpBriday = null;
DataRow[] selRows
= dtP.Select(filterStr);
for (int i = 0; i < selRows.Length;
i++)
{
    DataRow temp = selRows[i];
   
tmpName += temp["Name"] = textBox1.Text;
    tmpSexy +=
temp["Sexy"] = checkBox1.Checked ? 1 : 0;
    tmpBriday +=
temp["Briday"] = dateTimePicker2.Text;
    selRows[i] =
temp;
}

C# DataTable的用法