简体   繁体   English

在网格中显示数据

[英]Displaying data in a grid

I am new to C#, having done quite a bit of coding in VB6 in the past. 我是C#的新手,过去在VB6中做过很多编码。

I would like some advice on displaying data from a SQL database in a grid in a C# Windows Forms program. 我想要一些有关在C#Windows Forms程序中的网格中显示来自SQL数据库的数据的建议。 I have seen lots of ways to do this but I don't want to learn an obsolete method, so wondered if anyone could help. 我已经看到很多方法可以做到这一点,但是我不想学习过时的方法,所以想知道是否有人可以提供帮助。

The way I preferred to do this when I used VB6 was: 使用VB6时,我更喜欢这样做的方式是:

MS Access DB -> ODBC -> ADOConnection -> RecordSet -> MSFlexGrid MS Access DB-> ODBC-> ADOConnection-> RecordSet-> MSFlexGrid

I have seen the DataGridView in C# but don't think this is the method I would prefer. 我已经在C#中看到了DataGridView,但是不认为这是我更喜欢的方法。 That seems to be linked to a data source at design time, whereas the MSFlexGrid in VB6 was programatically populated at run time. 这似乎在设计时链接到数据源,而VB6中的MSFlexGrid是在运行时以编程方式填充的。 (I apologise if I have got this wrong). (如果我错了,我深表歉意)。

Basically, the perfect answer to this query would be link(s) to: 基本上,此查询的理想答案是链接到:

  1. A simple data access tutorial. 一个简单的数据访问教程。
  2. A round-up of all ways to display information in a grid. 在网格中显示信息的所有方式的汇总。

Use connection, and dataadapter class to fill DataTable. 使用连接和dataadapter类填充DataTable。 Then simply bind it to the gird by using DataSource property of the grid. 然后,只需使用网格的DataSource属性将其绑定到网格即可。 When creating a new instance of dataadapter, in parentheses define the sql query (select from ). 创建dataadapter的新实例时,请在括号中定义sql查询(从中选择)。 It should look simply like 它看起来应该像

DataTable table = new DataTable("myTable");
using(OdbcConnection conn = new OdbcConnection("specfiy_conn_string"))
{
    using(OdbcDataAdapter da = new OdbcDataAdapter(@"SELECT * FROM MyTable", conn))
        da.Fill(table);
}
dataGridView1.DataSource = table.DefaultView; //binding table to dgv

The datasource 'can' be linked at design time. 数据源“可以”在设计时链接。 Or you can just do it programmatically at runtime. 或者,您也可以在运行时以编程方式进行操作。 There are plenty of tutorials of this online. 在线上有很多教程。 Asking a question for people to send you links to tutorials only acknowledges that you know you could search for them yourself. 问一个问题给人们发送给您教程的链接只是承认您知道您可以自己搜索他们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM