这是我的Asp.net CodeBehindFile。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace binding
{
public partial class dataFromTable : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
stringstr=ConfigurationManager.ConnectionStrings["DefaultConnection"]
.ConnectionString;
using (SqlConnection con = new SqlConnection(str))
{
SqlCommand com = new SqlCommand("Select ID,CityID,CityName,Country from
City", con);
con.Open();
DropDownList1.DataSource = com.ExecuteReader();
DropDownList1.DataTextField = "CityName";
DropDownList1.DataValueField = "CityID"; DropDownList1.DataBind(); }
}
}
}
显示2个错误 第一个是:
发生了'System.Data.SqlClient.SqlException'类型的异常 System.Data.dll但未在用户代码中处理。
第二个错误是:
连接超时已过期。超时时间已过 尝试使用登录前握手确认。这个 可能是因为登录前握手失败或服务器失败了 无法及时回复。尝试时花费的时间 连接到此服务器 - [预登录]初始化= 26285; 握手= 912;
答案 0 :(得分:0)
您可以使用SqlDataAdapter
填充离线DataTable
,您可以将DataSource
用作DropDownList
。另外,对实现using
的对象使用IDisposable
- 语句:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable tblCities = new DataTable();
string conStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var con = new SqlConnection(conStr))
using (var com = new SqlCommand("Select ID,CityID,CityName,Country from City", con))
using (var da = new SqlDataAdapter(com))
da.Fill(tblCities); // you dont need to open/close the connection with Fill
DropDownList1.DataSource = tblCities;
DropDownList1.DataTextField = "CityName";
DropDownList1.DataValueField = "CityID";
DropDownList1.DataBind();
}
}
不要在每次回发时对其进行数据绑定,否则会阻止事件并取消选择。使用!IsPostBack
- 检查,如上所述..