最简单的
窗体代码写以下这些就可以了
sql = "select * from xxxx"
Datatable dt = xx.chaxun(sql)
datagridview1.DataSource = dt
记得将datagridview里面的字段与表中的字段相关联
Dateset 或DataTable或集合进行数据绑定,如有什么问题,请继续追问 private DataSet ds = new DataSet()
private SqlDataAdapter adapter = new SqlDataAdapter()//创建数据适配器
SqlCommand com = new SqlCommand("select TeacGuid, TeacName as 姓名,TeacSex as 性 别,TeacSalary as 工资,TeacRemark as 备注 from Teachers", DBHelper.con)
adapter.SelectCommand = com
adapter.Fill(ds, "Teachers")//将按照条件查出来的Teachers表中信息填充到ds中
this.dataGridView1.DataSource = ds.Tables["Teachers"]附上一段用DataSet实现的代码。
针对DataGridView中已进行过数据绑定,即已向DataGridView中添加了一些数据,可以结合Linq查询,并让匹配查询的行高亮显示,具体实现如下:
using Systemusing System.Collections.Generic
using System.Linq
using System.Windows.Forms
namespace Maxes_PC_Client {
public partial class frmWelcome : Form {
private int beforeMatchedRowIndex = 0
public frmWelcome()
{
InitializeComponent()
}
private void frmWelcome_Load(object sender, EventArgs e) {
this.dataGridViewInit()
}
/// <summary>
/// DataGridView添加数据、初始化
/// </summary>
private void dataGridViewInit() {
Dictionary<String, String> map = new Dictionary<String, String>()
map.Add("Lily", "22")
map.Add("Andy", "25")
map.Add("Peter", "24")
// 在这里必须创建一个BindIngSource对象,用该对象接收Dictionary<T, K>泛型集合的对象
BindingSource bindingSource = new BindingSource()
// 将泛型集合对象的值赋给BindingSourc对象的数据源
bindingSource.DataSource = map
this.dataGridView.DataSource = bindingSource
}
private void SearchButton_Click(object sender, EventArgs e) {
if (this.KeyWord.Text.Equals("")) {
return
}
// Linq模糊查询
IEnumerable<DataGridViewRow> enumerableList = this.dataGridView.Rows.Cast<DataGridViewRow>()
List<DataGridViewRow> list = (from item in enumerableList
where item.Cells[0].Value.ToString().IndexOf(this.KeyWord.Text) >= 0
select item).ToList()
// 恢复之前行的背景颜色为默认的白色背景
this.dataGridView.Rows[beforeMatchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.White
if (list.Count > 0) {
// 查找匹配行高亮显示
int matchedRowIndex = list[0].Index
this.dataGridView.Rows[matchedRowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Yellow
this.beforeMatchedRowIndex = matchedRowIndex
}
}
}
}
把DGV数据放到datatable DataTable dt = new DataTable()for (int j = 0j <ucgrd.Columns.Countj++) { dt.Columns.Add(ucgrd.Columns[j].HeaderCell.Value.ToString())} for (int j = 0j <ucgrd.Rows.Countj++) { DataRow dr = dt...
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)