DataGridView:顯示數據表,通過此控制項中可以實現連接資料庫,實現數據的增刪改查 一、後臺數據綁定: List<xxx> list = new List<xxx>(); dataGridView1.DataSource = list; //設置不自動生成列,此屬性在屬性面板中沒有 dataG ...
DataGridView:顯示數據表,通過此控制項中可以實現連接資料庫,實現數據的增刪改查
一、後臺數據綁定:
List<xxx> list = new List<xxx>();
dataGridView1.DataSource = list;
//設置不自動生成列,此屬性在屬性面板中沒有
dataGridView1.AutoGenerateColumns = false;
//取消載入預設選中第一行
dataGridView1.ClearSelection();
二、前臺:
小三角箭頭,取消可編輯,添加,刪除功能;
Columns集合屬性中,添加列
HeaderText中設置顯示的文本
DataPropertyName設置綁定的欄位名或資料庫列名
SelectionMode --設置選擇方式,FullRowSelect只能選中行
MultiSelect --是否可以選中多行內容
三、取值:
取出選中的單元格的值:
dataGridView1.SelectedCells中放著全部選中的單元格
if(dataGridView1.SelectedCells.Count > 0)
{
MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());
}
取出選中的行內容:
if(dataGridView1.SelectedRows.Count > 0)
{
MessageBox.Show(dataGridView1.SelectedRows[0].Cells[0].ToString());
}
獲取用於填充行綁定的對象:
//行對象使用屬性:DataBoundItem
student sss = dataGridView1.SelectedRows[0].DataBoundItem as student;
四、刪除加確認
MessageBoxButtons btn = MessageBoxButtons.YesNoCancel;
if (MessageBox.Show("確定要刪除麽?", "刪除數據", btn) == DialogResult.Yes)
{
}
五、多條件查詢
如果用戶什麼都不輸入,或者文本框是空,這時候是查詢所有
//做兩個恆成立的條件
string tj1 = " 1=1 ";
string tj2 = " 1=1 ";
//根據用戶輸入來改變條件
//如果用戶輸入了姓名
if (name != "")
{
tj1 = " Name like @name ";
}
//如果用戶輸入了民族
if (nation != "")
{
tj2 = " Nation = @nation ";
}
//拼接成完整條件
string ztj = " where "+tj1+" and "+tj2;
六、例子
通過控制項DataGridView,連接資料庫(表Student和表Sclass),實現對Student表的增刪改查
代碼區:
數據連接類:
namespace WindowsFormsApplication2 { public class DBConnect { private static string connstring = "server=.;database=xuesheng;user=sa;pwd=123"; public static SqlConnection Conn { get { return new SqlConnection(connstring); } } } }DBConnect.cs
實體類:
namespace WindowsFormsApplication2 { public class Student { private string sno; public string Sno { get { return sno; } set { sno = value; } } private string sname; public string Sname { get { return sname; } set { sname = value; } } private string ssex; public string Ssex { get { return ssex; } set { ssex = value; } } private DateTime sbirthday; public DateTime Sbirthday { get { return sbirthday; } set { sbirthday = value; } } private string sclass; public string Sclass { get { return sclass; } set { sclass = value; } } private string SclassName { get { SclassDA da = new SclassDA(); return da.SclassName(this.sclass); } } } }Student.cs
namespace WindowsFormsApplication2 { public class Sclass { private string cno; public string Cno { get { return cno; } set { cno = value; } } private string name; public string Name { get { return name; } set { name = value; } } } }Sclass.cs
數據訪問類:
namespace WindowsFormsApplication2 { public class StudentDA { private SqlConnection _conn; private SqlCommand _cmd; private SqlDataReader _dr; public StudentDA() { _conn = DBConnect.Conn; _cmd = _conn.CreateCommand(); } //查詢 public List<Student> Select() { List<Student> list = new List<Student>(); _cmd.CommandText = "select * from Student"; _conn.Open(); _dr = _cmd.ExecuteReader(); if (_dr.HasRows) { while (_dr.Read()) { Student data = new Student(); data.Sno = _dr[0].ToString(); data.Sname= _dr[1].ToString(); data.Ssex = _dr[2].ToString(); data.Sbirthday =Convert.ToDateTime( _dr[3]); data.Sclass = _dr[4].ToString(); list.Add(data); } } _conn.Close(); return list; } public Student Select(string sno) { _cmd.CommandText = "select * from Student where Sno=@sno"; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@sno",sno); _conn.Open(); _dr = _cmd.ExecuteReader(); Student data = new Student(); if (_dr.HasRows) { _dr.Read(); data.Sno = _dr[0].ToString(); data.Sname = _dr[1].ToString(); data.Ssex = _dr[2].ToString(); data.Sbirthday = Convert.ToDateTime(_dr[3]); data.Sclass = _dr[4].ToString(); } _conn.Close(); return data; } //刪除 public void Delete(string sno) { _cmd.CommandText = "delete from Student where Sno=@sno"; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@sno",sno); _conn.Open(); _cmd.ExecuteNonQuery(); _conn.Close(); } //多條件查詢 public List<Student> Select(string sname,string sclass) { //做兩個恆等條件 string tj1 = " 1=1 "; string tj2 = " 1=1 "; //根據用戶輸入改變條件 //用戶輸入了姓名 if(sname !="") { tj1 = " Sname like @sname "; } //用戶輸入了班級 if(sclass !="") { tj2 = " Class = @sclass "; } //拼接成完整的條件 string tj = " where " + tj1 + " and " + tj2; List<Student> list = new List<Student>(); _cmd.CommandText = "select * from Student"+tj; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@sname","%"+sname+"%"); _cmd.Parameters.AddWithValue("@sclass",sclass); _conn.Open(); _dr = _cmd.ExecuteReader(); if (_dr.HasRows) { while (_dr.Read()) { Student data = new Student(); data.Sno = _dr[0].ToString(); data.Sname = _dr[1].ToString(); data.Ssex = _dr[2].ToString(); data.Sbirthday = Convert.ToDateTime(_dr[3]); data.Sclass = _dr[4].ToString(); list.Add(data); } } _conn.Close(); return list; } //修改 public void Update(string sno, string sname, string ssex, DateTime sbirthday,string sclass) { _cmd.CommandText = "update Student set Sname=@sname,Ssex=@ssex,Sbirthday=@sbirthday,Class=@sclass where Sno = @sno"; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@sno", sno); _cmd.Parameters.AddWithValue("@sname", sname); _cmd.Parameters.AddWithValue("@ssex", ssex); _cmd.Parameters.AddWithValue("@sbirthday", sbirthday); _cmd.Parameters.AddWithValue("@sclass", sclass); _conn.Open(); _cmd.ExecuteNonQuery(); _conn.Close(); } //添加 public bool Add(string sno, string sname,string ssex,DateTime sbirthday,string sclass) { _cmd.CommandText = "insert into Student values(@sno,@sname,@ssex,@sbirthday,@sclass)"; _cmd.Parameters.Clear(); _cmd.Parameters.AddWithValue("@sno", sno); _cmd.Parameters.AddWithValue("@sname", sname); _cmd.Parameters.AddWithValue("@ssex", ssex); _cmd.Parameters.AddWithValue("@sbirthday", sbirthday); _cmd.Parameters.AddWithValue("@sclass", sclass); _conn.Open(); int n = _cmd.ExecuteNonQuery(); _conn.Close(); if (n > 0) { return true; } else { return false; } } } }StudentDA.cs
namespace WindowsFormsApplication2 { public class SclassDA { private SqlConnection _conn; private SqlCommand _cmd; private SqlDataReader _dr; public SclassDA() { _conn = DBConnect.Conn; _cmd = _conn.CreateCommand(); } public List<Sclass> Select() { List<Sclass> list = new List<Sclass>(); _cmd.CommandText = "select * from Sclass"; _conn.Open(); _dr = _cmd.ExecuteReader(); if (_dr.HasRows) { while (_dr.Read()) { Sclass data = new Sclass(); data.Cno = _dr[0].ToString(); data.Name= _dr[1].ToString(); list.Add(data); } } _conn.Close(); return list; } public string SclassName(string cno) { string name = "95031"; _cmd.CommandText = "select Name from Sclass where Cno=@cno"; _cmd.Parameters.AddWithValue("@cno", cno); _conn.Open(); _dr = _cmd.ExecuteReader(); if (_dr.HasRows) { _dr.Read(); name = _dr[0].ToString(); } _conn.Close(); return name; } } }SclassDA.cs
主窗體:
namespace WindowsFormsApplication2 { public partial class Form1 : Form { public static int bs = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { StudentDA da = new StudentDA(); //綁定數據源 dataGridView1.DataSource = da.Select(); //取消自動顯示列 dataGridView1.AutoGenerateColumns = false; //取消選中第一行 dataGridView1.ClearSelection(); //給下拉列表綁定值 SclassDA nda = new SclassDA(); cmbbanji.DataSource = nda.Select(); cmbbanji.DisplayMember = "Name"; cmbbanji.ValueMember = "Cno"; } //刪除 private void txtshan_Click(object sender, EventArgs e) { MessageBoxButtons btn = MessageBoxButtons.YesNoCancel; if (MessageBox.Show("確定要刪除麽?", "刪除數據", btn) == DialogResult.Yes) { //取出選中行裡面綁定的對象 Student data = dataGridView1.SelectedRows[0].DataBoundItem as Student; StudentDA da = new StudentDA(); da.Delete(data.Sno); dataGridView1.DataSource = da.Select(); } } //修改 private void txtxiu_Click(object sender, EventArgs e) { if (dataGridView1.SelectedRows.Count > 0) { //取出選中項的主鍵值 Student data = dataGridView1.SelectedRows[0].DataBoundItem as Student; //打出修改窗體 XiuGai xg = XiuGai.NewXiuGai(data.Sno); //顯示窗體 xg.Show(); //xg.Owner = this; //讓修改窗體獲得焦點 xg.Focus(); } else { MessageBox.Show("沒有選中任何項!"); } } //查詢 private void txtcha_Click(object sender, EventArgs e) { //取數據 string sname = txtxing.Text; string sclass = cmbbanji.SelectedValue.ToString(); //根據條件查詢,結果交給datagirdview顯示 StudentDA da = new StudentDA(); dataGridView1.DataSource = da.Select(sname,sclass); dataGridView1.AutoGenerateColumns = false; } //時鐘工具間隔執行的事件,刷新主窗體 private void timer1_Tick(object sender, EventArgs e) { if (bs == 1) { StudentDA da = new StudentDA(); dataGridView1.DataSource = da.Select(); bs = 0; } //if (Convert.ToInt32(this.Tag) == 1) //{ // StudentDA da = new StudentDA(); // dataGridView1.DataSource = da.Select(); // this.Tag = 0; //} } //添加 private void txttian_Click(object sender, EventArgs e) { //打出修改窗體 XiuGai xg = new XiuGai(); //顯示窗體 xg.Show(); //xg.Owner = this; //讓修改窗體獲得焦點 xg.Focus(); } } }Form1.cs
修改添加窗體:
namespace WindowsFormsApplication2 { public partial class XiuGai : Form { //用來存儲傳遞過來的主鍵值 private string Sno = ""; //用來存儲該類的對象 private static XiuGai xg = null; public XiuGai() { InitializeComponent(); } public XiuGai(string sno) { InitializeComponent(); this.Sno = sno; } private void XiuGai_Load(object sender, EventArgs e) { if (Sno != "") { txtsno.ReadOnly = true; //給下拉列表綁定值 SclassDA nda = new SclassDA(); cmbsclass.DataSource = nda.Select(); cmbsclass.DisplayMember = "Name"; cmbsclass.ValueMember = "Cno"; //對界面內容進行初始化 StudentDA da = new StudentDA(); Student data = da.Select(Sno); txtsno.Text = data.Sno; txtsname.Text = data.Sname; bool sex = (data.Ssex == "男" ? true : false); rdnan.Checked = sex; rdnv.Checked = !sex; txtsbirthday.Text = data.Sbirthday.ToString("yyyy-MM-dd HH:mm:ss"); } else { SclassDA nda = new SclassDA(); cmbsclass.DataSource = nda.Select(); cmbsclass.DisplayMember = "Name"; cmbsclass.ValueMember = "Cno"; } } //返回對象的方法 public static XiuGai NewXiuGai(string sno) { if (xg == null || xg.IsDisposed) { xg = new XiuGai(sno); } return xg; } //修改 private void button1_Click(object sender, EventArgs e) { //獲取數據 string _sno = txtsno.Text; string _sname = txtsname.Text; string _ssex=(rdnan.Checked==true?"男":"女"); DateTime _sbirthday = Convert.ToDateTime(txtsbirthday.Text); string _sclass = cmbsclass.SelectedValue.ToString(); StudentDA ida = new StudentDA(); ida.Update(_sno, _sname, _ssex, _sbirthday, _sclass); //this.Owner.Tag = 1; //給Form1的成員變數bs賦值 Form1.bs = 1; this.Close(); } //查詢 private void button2_Click(object sender, EventArgs e) { string _sno = txtsno.Text; string _sname = txtsname.Text; string _ssex = (rdnan.Checked == true ? "男" : "女"); DateTime _sbirthday = Convert.ToDateTime(txtsbirthday.Text); string _sclass = cmbsclass.SelectedValue.ToString(); StudentDA ida = new StudentDA(); ida.Add(_sno, _sname, _ssex, _sbirthday, _sclass); //this.Owner.Tag = 1; Form1.bs = 1; this.Close(); } } }XiuGai.cs
效果顯示區:
主窗體:
刪除:
添加:
修改:
查詢:
※數據區別顯示
//遍歷datagridview裡面行的集合,取出每一個行
foreach (DataGridViewRow row in dataGridView1.Rows)
{
//將該行裡面綁定的數據項取出
Info data = row.DataBoundItem as Info;
//判斷是不是男女
if (data.Sex)
{
}
}