gpt4 book ai didi

C#:无法以编程方式填充 DataGridView

转载 作者:行者123 更新时间:2023-11-30 15:08:29 25 4
gpt4 key购买 nike

我没有使用设计器,而是试图填充一个 DataGridView,我已经以编程方式放在我的 Winform 上。当我查看调试器下的表格时,它具有正确的列和行数。问题是网格在我的表单上显示为一个空的灰色框。当我通过 VS 2008 Designer 将网格绑定(bind)到数据库时,它工作正常。如何追踪问题?

更新

我几乎是从这个MSDN Article

更新

除了将网格放到 Winform 上之外,我是否需要在设计器中做任何事情?

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Windows.Forms;

namespace CC
{
public partial class Form1 : Form
{

private BindingSource bindingSource1 = new BindingSource();
private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();

public Form1()
{
InitializeComponent();
dataGridView1 = new DataGridView();

this.Load += new System.EventHandler(Form1_Load);
this.Text = "Cars";
}

private void Form1_Load(object sender, EventArgs e)
{

dataGridView1.DataSource = bindingSource1;
GetData("select * from Cars");


}

private void GetData(string selectCommand)
{
string dbPath = "c:\\temp\\cars.db";

try
{

var connectionString = "Data Source=" + dbPath + ";Version=3";

dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);

SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);


DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;

// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}


}
}

最佳答案

我认为您需要指定 DataMember 属性。而且我认为您不需要绑定(bind)源对象,您可以直接将 DataTable 绑定(bind)到 DataGridView 控件。

我附上了一个代码,它有助于将 gridview 控件与 SQL Server 数据库绑定(bind),它对我来说工作正常。

using(SqlDataAdapter sqlDataAdapter = 
new SqlDataAdapter("SELECT * FROM Table1",
"Server=.\\SQLEXPRESS; Integrated Security=SSPI; Database=SampleDb"))
{
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
this.dataGridView1.DataSource = dataTable;
}
}

抱歉,我没有安装 SQLite :(

关于C#:无法以编程方式填充 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5486439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com