在winform中用Datatable模擬數據庫做簡單的增刪改查


 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的做的小東西,看我首頁隨筆就行了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM