【发布时间】:2018-08-20 17:09:46
【问题描述】:
我在使用 SQLAdapter 时遇到了一些问题。运行以下代码时,我最终得到一个重复行的数据表。我无法弄清楚问题出在哪里。我已经谷歌了,几乎所有的帖子都处理从 sql DB 读取的重复数据。我的数据库表中有 4 条记录。那里不可能有重复的数据。
using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
public partial class Vehicles : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadResources();
VehicleScheduler1.StartDate = new DateTime(DateTime.Today.Year, 1, 1);
VehicleScheduler1.DataBind();
}
}
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["DayPilot"].ConnectionString;
}
private void LoadResources()
{
VehicleScheduler1.Resources.Clear();
string sql = "SELECT [id], [name] FROM [vehicles]";
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
da.Fill(dt);
foreach (DataRow r in dt.Rows)
{
string name = (string)r["name"];
string id = Convert.ToString(r["id"]);
VehicleScheduler1.Resources.Add(name, id);
conn.Close();
}
}
}
[EndResult][1]}
【问题讨论】:
-
您正在加载和填充数据表。做一个或另一个。
标签: c# sql sqldatareader sqldataadapter