添加数据源后,如何访问?
Posted
技术标签:
【中文标题】添加数据源后,如何访问?【英文标题】:After adding data source, how do I access it? 【发布时间】:2012-03-06 15:49:51 【问题描述】:我已经在我的 c# 项目中添加了一个访问数据库数据源,现在我希望能够使用 C# 访问数据。如果我右键单击数据源并按“预览数据”,我可以看到来自数据源的数据,但我不知道使用什么代码来访问这些数据。
在预览菜单中,它显示了两个方法 .Fill 和 GetData(),但我不知道如何访问它们。
任何帮助将不胜感激,谢谢!
【问题讨论】:
我不知道“预览菜单”,但 Fill 和 GetData 属于 DataDapater。现在您有足够的关键字可以一起搜索教程。 你想将数据绑定到什么?一个数据视图或什么控件? 【参考方案1】:听起来您正在查看出现在 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;
Dev XVB
中的文章,但它给了你这个想法:
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.");
【讨论】:
【参考方案2】:我知道这是一个老问题,它有一个公认的答案,但答案似乎没有正确解决这个问题。
在我看来,问题是关于使用向导创建的数据源、数据集和数据表,因为该问题提到了预览数据。我今天正好遇到了这个问题。我不想用要填充我自己的字典的数据填充控件。
这是我的解决方案:
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 中显示其他表,因此创建新的类和对象来访问它似乎很愚蠢。
【讨论】:
以上是关于添加数据源后,如何访问?的主要内容,如果未能解决你的问题,请参考以下文章