C#比较SQL Server Database 2005中2个表的值,并在VS2005的Gridview中显示

时间:2011-11-11 02:34:00

标签: c# sql-server visual-studio sql-server-2005 visual-studio-2005

我正在使用VS2005 C#和SQL Server Database 2005.

我想要比较2个数据库之间的值。

我能够通过SELECT WHERE sql语句从tStudent Table中检索变量[StudentName],如下所示: enter image description here enter image description here

现在,我有另一个名为StudentDetails的表。它有3列,StudentName,Address和ContactNum: enter image description here

情况是我希望从tStudent上的第一个SQL查询中获取结果,该查询返回一个[Status] = DELETED的学生列表。

从查询的学生名单中,我想一次带一名学生,并搜索我的[学生详细信息]表。

如果它存在于[StudentDetails]中,我想使用一种方法来存储StudentDetails表中的变量[StudentName]并在我的网页上的GridView中显示它。 (这里有很多解决方案。存储在数据库中;在GridView中显示结果;存储在数组中;等等)

我可以知道我可以采取哪些方法和步骤来实现结果?

非常感谢分步指南和代码片段,因为我在C#编程方面相当薄弱。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

  • 使用Visual Studio创建DataSet名称StudentDS,在此DataSet中创建表名“Student”,此表将包含3个表列:String StudentName;字符串地址; String ContactNum;
  • 将已删除的学生填入此DataSet:

DataSet dset = new StudentDS(); String connectionString =“”; //取决于您的数据库系统,请参阅http://www.connectionstrings.com

        using (connection = new OdbcConnection(connectionString))
        {
            connection.Open();

            command.Connection = connection;
            command.CommandText = "select StudentName, Address, ContactNum from tStudent WHERE status = 'DELETE'";

        OdbcDataAdapter da = new OdbcDataAdapter();
        da.SelectCommand = command;

        da.Fill(dset, "Student");
    }

- 获得此DataSet后,您可以迭代其行以执行您想要的操作。

if(dset.Tables[0].Rows != null) {
for (int i = 0; i < dset.Tables[0].Rows.Count, i++){
if(!ExistInStudentDetail(dset.Tables[0].Rows[i]["StudentName"]))
{
dset.Tables[0].Rows.remove(i);
i--;
}
}
}

//这里,boolean ExistInStudentDetail(String StudentName)是一个方法,你可以为此创建sql,如上所述。

  • 在表单中,添加一个新的DataGridView名称“StudentForm”,为此DataGridView名称“StudentName”添加1列,并将其绑定属性设置为“StudentName”(DataSet中的相同列名),然后设置此DataSource网格。 StudentForm.DataSource = dSet;

HTH。

答案 1 :(得分:0)

这是一个相当简单的问题,但范围非常大。所以这里:

首先,您应该确保在搜索的表中有唯一的列,这样您就可以修改这些单独的行,并确保修改正确的行。我没有在截图中看到任何ID列,所以我只是想覆盖它。

其次,我会为学生创建一个课程。在这里,我将创建我想要的所有信息的字段或属性。

class Student
{
  public string Name { get; private set; }
  public string Address { get; private set; }
  public string ContactNum { get; private set; }
}

您可以使用上述类中的构造函数并使用该属性填充属性,也可以通过选择您的选择来填写每个属性。

第三,我会创建一个List<Student> students;,这将用作参考列表

List<Student> deletedStudents = SQL Select Statement;

第四,我将创建另一个List<Student> detailedStudents;

最后,我会比较两个列表,然后在找到匹配项时执行某些操作。