1 //简单的建一个表 2 private void FormDT_Load(object sender, EventArgs e) 3 { 4 dt.Columns.Add("A", typeof(String)); 5 dt.Columns.Add("B", typeof(String)); 6 dt.Columns.Add("C", typeof(String)); 7 dt.Rows.Add("101", "102", "103"); 8 dt.Rows.Add("100", "102", "103"); 9 dt.Rows.Add("111", "102", "104"); 10 this.dataGridView1.DataSource = dt; 11 this.dataGridView1.AutoGenerateColumns = false; 12 }
//添加 private void button1_Click(object sender, EventArgs e) { DataRow dr = dt.NewRow(); dr["A"] = textBox1.Text; dr["B"] = textBox2.Text; dr["C"] = textBox3.Text; if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "") { MessageBox.Show("请完整填写数据"); if (textBox3.Text == "") { textBox3.Focus(); } if (textBox2.Text=="") { textBox2.Focus(); } if (textBox1.Text=="") { textBox1.Focus(); } } else { dt.Rows.Add(dr); } }
//修改,if里是非空验证和设置鼠标焦点 private void button2_Click(object sender, EventArgs e) { if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "") { MessageBox.Show("请完整填写数据"); if (textBox3.Text == "") { textBox3.Focus(); } if (textBox2.Text == "") { textBox2.Focus(); } if (textBox1.Text == "") { textBox1.Focus(); } } else { DataRow dr = dt.Rows[dataGridView1.CurrentCell.RowIndex]; dr.BeginEdit(); dr["A"] = textBox1.Text; dr["B"] = textBox2.Text; dr["C"] = textBox3.Text; dr.EndEdit(); } }
//删除,非空验证和修改里的差不多 private void button3_Click(object sender, EventArgs e) { double sum = 0; for (int i = 0; i < dataGridView1.Rows.Count; i++) { sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value); } if (sum == 0) { MessageBox.Show("数据已经为空"); } else { dt.Rows.RemoveAt(dataGridView1.CurrentCell.RowIndex); } }
运行之后,这个是运行后的初始样子。过两天我会发一个更详细的,多窗体的用datatable的做的小东西,看我首页随笔就行了