可视化方式绑定 DataGridView 控件(写的不详细,结合上一篇)
使用可视化数据绑定方式可以快速完成将数据表中的数据显示在 DataGridView 控件中的操作,并可以很容易地对绑定列的属性进行相关设置。(可以看到代码减少了很多)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“myDataSet.StuCourse”中。您可以根据需要移动或删除它。
this.stuCourseTableAdapter.Fill(this.myDataSet.StuCourse);
dgv.MultiSelect = false;
dgv.Columns[0].ReadOnly = true;
}
private void btnSearch_Click(object sender, EventArgs e)
{
dgv.DataSource = null;
dgv.DataSource = this.stuCourseTableAdapter.GetDataBy(cbCourseName.SelectedValue.ToString());
}
private void btnDelete_Click(object sender, EventArgs e)
{
int id = -1;
bool isTrue = int.TryParse(dgv.SelectedRows[0].Cells[0].Value.ToString(), out id);
if (!isTrue)
{
MessageBox.Show("ERROR");
return;
}
this.stuCourseTableAdapter.DeleteTheCourseInfo(id);
dgv.DataSource = null;
this.stuCourseTableAdapter.Fill(this.myDataSet.StuCourse);
dgv.DataSource = this.stuCourseBindingSource1;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dgv.SelectedRows.Count <= 0)
{
MessageBox.Show("ERROR");
return;
}
int id = Convert.ToInt32(dgv.SelectedRows[0].Cells[0].Value);
string name = dgv.SelectedRows[0].Cells[1].Value.ToString();
decimal credit = Convert.ToDecimal(dgv.SelectedRows[0].Cells[2].Value);
string remark = dgv.SelectedRows[0].Cells[3].Value.ToString();
this.stuCourseTableAdapter.UpdateTheCourseInfo(name, credit, remark, id);
dgv.DataSource = null;
this.stuCourseTableAdapter.Fill(this.myDataSet.StuCourse);
dgv.DataSource = this.stuCourseBindingSource1;
}
}