我已将访问数据库数据源添加到我的c#项目中,现在我希望能够使用C#访问数据。如果我右键单击数据源并按“预览数据”,我可以看到数据源中的数据,但我不知道用什么代码来访问这些数据。
在预览菜单中,它显示了两个方法.Fill和GetData(),但我不知道如何访问这些方法。
任何帮助将不胜感激,谢谢!
答案 0 :(得分:2)
听起来您正在查看DataSet表适配器上显示的Fill / GetData方法。有很多资源可以举例说明如何绑定数据,包括这里,我会建议查看一些示例以了解如何操作(以下示例适用于datagridviews
):
来自C#: Can't populate DataGridView programatically:
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;
}
}
VB
中的Dev X文章,但它为您提供了这个想法:
Dim connStr As String = _
"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;" & _
"Integrated Security=True"
Dim sql As String = "SELECT * FROM Customers"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)
Dim dataadapter As SqlDataAdapter = New SqlDataAdapter(comm)
Dim ds As DataSet = New DataSet()
'---open the connection and fill the dataset---
conn.Open()
'---fill the dataset---
dataadapter.Fill(ds, "Customers_table")
'---close the connection---
conn.Close()
'---bind to the DataGridView control---
DataGridView1.DataSource = ds
'---set the table in the dataset to display---
DataGridView1.DataMember = "Customers_table"
来自MSDN Bind Data to the Windows Forms DataGridView Control
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public class Form1 : System.Windows.Forms.Form
{
private DataGridView dataGridView1 = new DataGridView();
private BindingSource bindingSource1 = new BindingSource();
private SqlDataAdapter dataAdapter = new SqlDataAdapter();
private Button reloadButton = new Button();
private Button submitButton = new Button();
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
// Initialize the form.
public Form1()
{
dataGridView1.Dock = DockStyle.Fill;
reloadButton.Text = "reload";
submitButton.Text = "submit";
reloadButton.Click += new System.EventHandler(reloadButton_Click);
submitButton.Click += new System.EventHandler(submitButton_Click);
FlowLayoutPanel panel = new FlowLayoutPanel();
panel.Dock = DockStyle.Top;
panel.AutoSize = true;
panel.Controls.AddRange(new Control[] { reloadButton, submitButton });
this.Controls.AddRange(new Control[] { dataGridView1, panel });
this.Load += new System.EventHandler(Form1_Load);
this.Text = "DataGridView databinding and updating demo";
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Bind the DataGridView to the BindingSource
// and load the data from the database.
dataGridView1.DataSource = bindingSource1;
GetData("select * from Customers");
}
private void reloadButton_Click(object sender, System.EventArgs e)
{
// Reload the data from the database.
GetData(dataAdapter.SelectCommand.CommandText);
}
private void submitButton_Click(object sender, System.EventArgs e)
{
// Update the database with the user's changes.
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}
private void GetData(string selectCommand)
{
try
{
// Specify a connection string. Replace the given value with a
// valid connection string for a Northwind SQL Server sample
// database accessible to your system.
String connectionString =
"Integrated Security=SSPI;Persist Security Info=False;" +
"Initial Catalog=Northwind;Data Source=localhost";
// Create a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
// Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
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.");
}
}
}
答案 1 :(得分:0)
我知道这是一个古老的问题,并且已经接受了答案,但是该答案似乎无法正确解决该问题。
我看到的问题是关于使用向导创建的数据源,数据集和数据表,因为该问题涉及预览数据。我今天确实有这个问题。我不想用我想填充自己的字典的数据来填充控件。
这是我的解决方法:
private static Dictionary<string, InstrumentTransformer> InitInstrumentTransformers()
{
var result = new Dictionary<string, InstrumentTransformer>();
using (var adapter = new _TSTAT_SETUPDataSetTableAdapters.SetupInstrumentTransformersTableAdapter())
{
var table = adapter.GetData();
foreach (var row in table)
{
var instrumentTransformer = new InstrumentTransformer(row);
result[instrumentTransformer.TransformerID] = instrumentTransformer;
}
}
return result;
}
TSTAT_SETUP是Access mdb的名称,SetupInstrumentTransformers是其中的表的名称。 TransformerID是主键。
结果是对象字典,其中每个对象都是从数据库中的一行创建的。
之所以这样做,是因为我已经设置了数据源以在datagridviews中显示其他表,因此创建新的类和对象来访问它似乎很愚蠢。