【问题标题】:Display Lesson Names instead of Lesson Codes in the grid with BindingSource or with some other method使用 BindingSource 或其他方法在网格中显示课程名称而不是课程代码
【发布时间】:2014-12-27 20:55:16
【问题描述】:

我在数据库中有一个数据。我读取了这些数据并将其显示在网格中。为此,我使用DataSet, SqlDataAdapter, BindingSource and DataGridView
表格如下所示。

+---------+------------+-------------+
|   NAME  |   SURNAME  | LESSON_CODE |
+---------+------------+-------------+
|  Joe    |  Black     |  110        |          
|  Mia    |  Sommers   |  120        | 
|  Hasan  |  Almalik   |  100        | 
|  Anna   |  Volkova   |  100        | 
|  Robert |  Jackson   |  115        | 
|  Tony   |  Bernard   |  120        | 
|  Diana  |  Albert    |  115        | 
|  Tom    |  Bruce     |  110        |
+---------+------------+-------------+

我像这个 sql 查询一样从表中读取这些数据。

string sql = "SELECT Name, Surname, Lesson_Code as Lesson FROM Class"
SqlDataAdapter adapter  = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand(sql,connection);
adapter.SelectCommand = selectCommand;

DataSet ds = new DataSet();
adapter.Fill(ds,"Class");

BindingSource bs = new BindingSource(ds,"Class");
gridClass.DataSource = bs;

好的。没有任何问题。
但我不想在网格中显示课程代码。我有一个课程列表和课程代码。

100 - MATH  
110 - GEOMETRY  
115 - BIOLOGY  
120 - ASTRONOMY  
etc.

我不将此列表存储在数据库中。如果我将此列表存储在表中,我可以使用带有表连接的 sql 查询来解决此问题。
但我不想这样做。我不想使用 sql 查询。我想从代码中做到这一点。 所以我想我可以用 BindingSource 解决这个问题。但我不知道怎么做?或者可能有其他方法?

【问题讨论】:

  • 那么你有另一个表,里面有课程名称吗?
  • @namco 看起来您的问题在“我不存储此列表”时意外中断
  • 可以通过格式化来解决。见here

标签: c# sql data-binding datagridview


【解决方案1】:

如果您说您有另一个表,其中包含与代码关联的课程名称,那么您必须进行联接。您的查询应如下所示。

SELECT a.Lesson_Name, b.Surname, b.Name FROM LessonTable a, Class b WHERE a.Lesson_Code = b.Lesson_Code

【讨论】:

  • 我不想使用 sql 查询。有没有办法用代码做到这一点?
  • 不,我没有。我不想用sql查询来解决。
  • 问题本身明确提到了条件“不要使用sql查询”。
【解决方案2】:

我认为您想将结果绑定到数据表中。

然后使用一个新的数据表,用以前的数据表和你的课程列填充它

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2012-04-24
    • 1970-01-01
    • 2016-03-23
    相关资源
    最近更新 更多