从Web.config文件中的SQL连接字符串创建DataTable

本文关键字:连接 字符串 创建 DataTable SQL Web config 文件 | 更新日期: 2023-09-27 18:21:27

我需要在网页上显示SQL Server数据库中表中的数据。我的Web.config文件中有一个连接字符串,如下所示:

<connectionStrings>
<add name="Products.ConnectionString" 
     connectionString="Data Source=...."
     providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
  <compilation debug="true" targetFramework="4.5" />
  <httpRuntime targetFramework="4.5" />
</system.web>

在我的aspx中,我有一个带有ObjectDataSource的GridView来显示数据。在后面的代码中,我创建了一个List方法来返回数据库表中的值。然而,现在我被告知用户需要能够过滤数据,所以我创建了一个文本框和一个按钮来启用它,但后来意识到在这种情况下,使用DataTable比使用List更好。不过,我一直在为这类项目使用列表,所以我不确定如何在DataTable中实现这一点。以下是我的列表的代码:

 public class Products
{
    public string Name { get; set;} 
    public int Price { get; set; }

    public List<Products> DataTable()
    {
        List<Products> myList = new List<Products>();
        string sqlQuery = "SELECT * FROM [Products_Table] ";
        string connectionString = ConfigurationManager.ConnectionStrings["Products_ConnectionString"].ConnectionString; //Read connection string from config file

        using (var con = new SqlConnection(connectionString))
        {
            using (var cmd = new SqlCommand(sqlQuery, con))
            {
                con.Open(); //Open connection
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Products t = new Products();
                        t.Name = reader["Name"].ToString();
                        t.Price = Convert.ToInt32(reader["Price"]);

                        myList.Add(t);
                    }
                }
            }
        }
        return myList;
    }
}

因此,如果有人能让我走上正轨,首先用DataTable替换列表,那就太好了。

从Web.config文件中的SQL连接字符串创建DataTable

在您的代码中,您需要执行以下操作:

public static class ProductsDataSource
 {
public static DataTable LoadProducts()
 {
    using (SqlConnection conn = new   SqlConnection(ConfigurationManager.ConnectionStrings["Products_ConnectionString"].ConnectionString))
    using (SqlCommand command = new SqlCommand("SELECT * FROM Products_Table", conn))
    {
        DataTable data = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(data);
        return data;
    }
  }
}

由于您使用的是ObjectData Source,请确保正确定义SelectMethod和Typename以便返回数据。类似这样的东西:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="ProductsDataSource"
SelectMethod="LoadProducts" 
/>

类似的东西

GridView1.DataSource = DataTable();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
    string SQL = "SELECT * FROM [Table];";
    SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    GridView1.DataSource = dt;
    GridView1.DataBind();

我不知道你在寻找什么,但这就是你将GridView与DataTable绑定的方式。