似乎我的代码不完整或我的语法错误但是我尽力提出某种解决方案但到目前为止没有成功......所以这就是我想要做的: 我有几个下拉框,并希望将每个下拉框的选定值分配给表适配器中的值。到目前为止,这是我的代码,但不确定缺少什么:
protected void Page_Load(object sender, EventArgs e)
{
ID = Convert.ToInt32(Request.QueryString["myID"]);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT NAME, DEPARTMENT, LOCATION from MyTable WHERE ID = '" + ID + "' ", con);
DataTable dt= new DataTable();
da.Fill(dt);
ddl_Name.SelectedValue = dt[0].Name;
ddl_DEPARTMENT.SelectedValue = dt[0].DEPARTMENT;
ddl_LOCATION.SelectedValue = dt[0].LOCATION;
}
我的问题从这里开始,当我输入dt [0] .Name时,似乎它不喜欢我添加零。请帮忙。感谢
答案 0 :(得分:3)
dt
是没有索引器的DataTable
,您需要DataRow
字段,因此您需要先通过DataTable.Rows[index]
获取行:
if(dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
ddl_Name.SelectedValue = row.Field<string>("Name");
ddl_DEPARTMENT.SelectedValue = row.Field<string>("DEPARTMENT");
ddl_LOCATION.SelectedValue = row.Field<string>("LOCATION");
}
您无法直接访问该字段(没有强类型DataTable
)。您必须使用DataRow.Field
来获取字段的值或旧的弱类型索引器:
object name = row["Name"];
ViewState
(默认),然后将此代码块放入!IsPostBack
检查,否则SelectedIndexChanged
事件将不会触发,因为用户选择将被覆盖来自旧的数据库值。protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ID = Convert.ToInt32(Request.QueryString["myID"]);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT NAME, DEPARTMENT, LOCATION from MyTable WHERE ID = @ID", con);
DataTable dt= new DataTable();
da.SelectCommand.Parameters.AddWithValue("@ID", int.Parse(ID));
da.Fill(dt);
// Code above...
}
}