有一个无效 SelectedValue,因为它不在项目列表中
这个错误让我头疼了很长时间,在网上也查找了很多方法,但对我来说好像不奏效。
找来找去,最后还是决定用笨方法来解决。
protected void XX_DataBinding(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ddl.Items.Add("");
CreateDDL("select dataValue from daiBasicData where dataClass='XX' ", ddl);
DataRowView dr = (DataRowView)DetailsView1.DataItem;
int i = ddl.Items.IndexOf(ddl.Items.FindByValue(dr.Row["aField"].ToString()));
if (i == -1) i = 0;
ddl.SelectedValue = ddl.Items[i].Value;
}
private void CreateDDL(String sql, DropDownList ddl)
{
try
{
if (conn != null)
{
if (conn.State == ConnectionState.Open)
{
SqlCommand comd = new SqlCommand();
comd.Connection = conn;
comd.CommandText = sql;
SqlDataReader reader = comd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
if (reader[0] != System.DBNull.Value)
ddl.Items.Add(reader[0].ToString());
}
}
reader.Close();
comd.Dispose();
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}