using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataTable PretendImADataBase;
public Form1()
{
InitializeComponent();
PretendImADataBase = CreateTestData();
//this assigns the row enter event to this function. Each time the row changes,
//the function is called. Inside this function, you load your "big data" columns.
//That way, you only load 2 or 3 columns for all rows, and each time the row changes,
//you go back out and load all of the details for only that 1 row.
//Pretty basic way to load data..
dataGridView1.RowEnter += dataGridView1_RowEnter;
//initial loading, only 1 or 2 columns of large dataset, to keep loading time fast.
//primary key, and enough info to identify the full record.
dataGridView1.DataSource = CreateDataSource1();
}
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
//This is where you would make your database call to load big data.
var x = sender as DataGridView;
if (x.DataSource == null) return;
var id = x[0, e.RowIndex].Value;
DataRow oRow = (from DataRow row in PretendImADataBase.Rows where (int)row["FK"] == (int)id select row).FirstOrDefault();
if (!(oRow == null))
{
textBox1.Text = oRow[3].ToString();
textBox2.Text = oRow[4].ToString();
}
}
private DataTable CreateTestData()
{
DataTable oDt = new DataTable();
DataColumn oCol = new DataColumn("ID", typeof(int));
oDt.Columns.Add(oCol);
oCol = new DataColumn("FK", typeof(int));
oDt.Columns.Add(oCol);
oCol = new DataColumn("Data1", typeof(string));
oDt.Columns.Add(oCol);
oCol = new DataColumn("Data2", typeof(string));
oDt.Columns.Add(oCol);
DataRow oRow = oDt.NewRow();
oRow["ID"] = 1;
oRow["FK"] = 1;
oRow["Data1"] = "Test Data 1";
oRow["Data2"] = "Test Data 2";
oDt.Rows.Add(oRow);
oRow = oDt.NewRow();
oRow["ID"] = 2;
oRow["FK"] = 2;
oRow["Data1"] = "Test Data 3";
oRow["Data2"] = "Test Data 4";
oDt.Rows.Add(oRow);
return oDt;
}
private DataTable CreateDataSource1()
{
DataTable oDt = new DataTable();
DataColumn oCol = new DataColumn("ID",typeof(int));
oDt.Columns.Add(oCol);
oCol = new DataColumn("Display", typeof(string));
oDt.Columns.Add(oCol);
DataRow oRow = oDt.NewRow();
oRow["ID"] = 1;
oRow["Display"] = "Test 1";
oDt.Rows.Add(oRow);
oRow = oDt.NewRow();
oRow["ID"] = 2;
oRow["Display"] = "Test 2";
oDt.Rows.Add(oRow);
return oDt;
}
}
}
3条答案
按热度按时间vyu0f0g11#
根据你的评论,这里是如何在数据网格视图中改变行的数据。你需要改变它来进行实际的数据库调用。我做了一个小表作为例子。为了工作,做一个新的winforms应用程序,在上面放一个DataGridView和2个文本框
lx0bsm1f2#
不确定我是否得到了您想要的,但是,您正在使用DataGridView的数据源来绑定结果,对吗?如果是这样,在您选择了数据源之后,您可以隐藏您不想显示的列,如下所示:
这样,网格将只显示所需的列,但当单击事件触发时,您可以访问隐藏的列以在控件上显示它们。
aurhwmvo3#
你可以做这个简单的任务。
1.您必须将GridView中的所有列添加为表单上的文本字段。
1.可以将要显示的列的Visible属性设置为true,否则可以通过将此属性设置为false来隐藏。
1.现在,您将能够使用CellDoubleClick、CellClick、RowDoubleClick或RowClick事件将行数据填充到窗体上的相关字段中。
1.您必须将网格视图AutoGenerateColumns的属性设置为False,并且每个数据表列名的名称要使用DataGridViewProperty与网格视图列进行Map。