创建一个查询并将结果放入datagrid

时间:2011-12-04 11:35:30

标签: c# sql sql-server

我有一张桌子

idteacher idstudent idsubject studentname subjectname teacherame mark

但如何用表中的信息填充

idteacher teachername
idstudent studentname
idsubject subjectname

mark - 仅存在于此表中然后将其放入datagrid的字段?(我已经创建了datagrid和table(在visual studio-> Server explorer中))

3 个答案:

答案 0 :(得分:3)

如果我理解正确,您希望将SQL表中的数据绑定到ASP.NET gridview,如果是,则可以这样做:

代码背后:

    public System.Data.DataTable GetData()
    {
        System.Data.DataTable table = new System.Data.DataTable();
        string connectionString =
            System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (var command = new SqlCommand("GetCars", connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(table);
            }
            connection.Close();
        }
        return table;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        gridView.DataSource = GetData();
        gridView.DataBind();
    }

Web.config - 为了安全起见并允许在不同数据库之间轻松切换,将连接字符串存储在Web.config中:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <connectionStrings>
    <add name="connectionString" connectionString="Your connection string..."/>
  </connectionStrings>
</configuration>

存储过程:

CREATE PROCEDURE dbo.GetCars
AS
BEGIN
    SELECT * FROM Cars
    ORDER BY CarId DESC
END

您是否应该使用内联SQL语句或存储过程一直是一个非常有争议的主题,但从个人经验我同意Marc并使用它们具有以下优点:

  1. SP已预先编译以提高性能

  2. 减少SQL注入的攻击面积

  3. 允许您从应用程序中抽象出复杂的数据处理

答案 1 :(得分:2)

DataSourceDataGrid属性设置为您应加载的DataTable

答案 2 :(得分:2)

您可能需要数据库中的以下表格:

CREATE TABLE teacher (
    idteacher int,
    teachername nchar(50))

CREATE TABLE student (
    idstudent int,
    studentname nchar(50))

CREATE TABLE subject (
    idsubject int,
    subjectname nchar(50))

CREATE TABLE mark (
    idteacher int,
    idstudent int,
    idsubject int,
    mark int)

为简洁起见,我省略了主键和外键。然后,您将使用以下查询检索DataGrid的数据:

SELECT 
    t.idteacher,
    st.idstudent,
    s.idsubject,
    t.teachername,
    st.studentname,
    s.subjectname,
    m.mark
FROM mark m
    INNER JOIN teacher t ON m.idteacher = t.idteacher
    INNER JOIN student st ON m.idstudent = st.idstudent
    INNER JOIN subject s ON m.idsubject = s.idsubject

使用以上查询将数据加载到DataGrid使用Denys的GetData()方法。