1、dataGridView
- dataGridView是一个数据展示控件;
- 可以绑定集合
Class Students{
students中只能设置属性,而不能设置字段;因为dataGridView的数据绑定是通过反射来实现的,反射的过程中获取的类的属性而不是字段;
public int id { get; set; }
public string name { get; set; }
}
List<Students> list = new List<Students>();
// 使用对象初始化器
Students s = new Students
{
id = 1,
name = "张三"
};
// 数据绑定
dataGridView1.DataSource = list;
- 操作被选中行的数据:将SelectionMode设置为整行选中,MultSelection设置为false;
private void datadiv_RowEnter(object sender, DataGridViewCellEventArgs e)
{
// 获取被选中行的索引
int index = e.RowIndex;
// 获取被选中行的数据
DataGridViewRow data = datadiv.Rows[index];
// 将被选中行转换成list中存放的对象
Students s = data.DataBoundItem as Students;
if (s != null)
{
textBox3.Text = s.id.ToString();
textBox4.Text = s.name;
}
}
- 更改UI层显示的内容—CellFormatting事件
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//此处要保证不为null才可以修改
if(e.ColumnIndex == 4 && e.Value != null)
{
e.Value = (bool)e.Value == true ? "男" : "女";
}
}
2、提示框
参数:参考文章
- 显示的文本内容
- 提示框标题
- 按键
- 显示的图标
- 默认选中的按键
DialogResult result = MessageBox.Show("确定要删除吗?", "操作提示", MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
如果确认再删除
if (result == DialogResult.OK)
{
bbl.Delete(int.Parse(label9.Text));
LoadData();
}
3、窗体传值
1、静态类
public static class Test{
public static int id{get;set;}
}
4、TreeView
5、下拉框comboBox
- 先将数据库中的数据存储到list中,然后将list当作combobox的数据源;
comboBox1.DisplayMember = "要显示的内容的字段名";
comboBox1.ValueMember = "要显示的内容的id";
comboBox1.DataSource = list;
- 设置combobox中显示内容的索引
comboBox1.SelectedIndex = 0;
- 直接向combobox中添加内容
comboBox1.Items.Add("列表项");