【发布时间】:2016-04-15 05:13:19
【问题描述】:
我无法在下面获取我的代码来将我的 DropDownList 设置为正确的值。
else 语句中的代码对我不起作用,但也不会引发任何异常。
DropDownList 是从我存储程序信息的一个数据库中设置的。我使用reader1 访问的数据库是一个用户信息数据库,它具有从DropDownList 注册时选择的字符串值,所以我不能使用索引。有人可以指出我哪里出错了吗?
我只想从用户数据库中检索我的文本字符串,从程序数据库中填充 DropDownList,然后让数据库显示与字符串匹配的项目。它的最后一部分,自动选择项目,这就是问题所在。
private DataTable loadAdBusinessTypes1()
{
string prgInfoConnection = ConfigurationManager.ConnectionStrings["program_infoConnection"].ToString();
SqlConnection oSqlConnection = new SqlConnection(prgInfoConnection);
SqlCommand oSqlCommand = new SqlCommand();
oSqlCommand.Connection = oSqlConnection;
oSqlCommand.CommandType = CommandType.StoredProcedure;
oSqlCommand.CommandText = "pGetAdBusinessTypes";
SqlDataAdapter oSqlDataAdapter = new SqlDataAdapter();
oSqlDataAdapter.SelectCommand = oSqlCommand;
DataTable oDataTable1 = new DataTable("AdBusinessTypes");
oSqlDataAdapter.Fill(oDataTable1);
return oDataTable1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] == null)
{
Response.Redirect("~/Account/Login.aspx"); //*****CHANGE REDIRECT WEBPAGE*****
}
else
{
if (!Page.IsPostBack)
{
DataTable oDataTable = loadAdBusinessTypes1();
BusTypeddl.DataSource = oDataTable;
BusTypeddl.DataTextField = "business_type";
BusTypeddl.DataBind();
}
try
{
if (Session["New"] == null)
{
Response.Redirect("~/Account/Login.aspx"); //*****CHANGE REDIRECT WEBPAGE*****
}
else
{
string str = Convert.ToString(Session["New"]);
string cmdText = @"select account_no, first_name, last_name, email_1, email_2, business_street_1, business_street_2, business_street_3, business_city, business_state, business_postal_code, business_country, company_name, business_type, phone_1, phone_2, phonecode_1, phonecode_2, website, registration_date, screens_no, user_password from users where email_1 =@email";
string cpUsersConnection = ConfigurationManager.ConnectionStrings["cp_usersConnection"].ToString();
using (SqlConnection oSqlConnection = new SqlConnection(cpUsersConnection))
using (SqlCommand oSqlCommand = new SqlCommand(cmdText, oSqlConnection))
{
oSqlConnection.Open();
oSqlCommand.Parameters.Add("@email", SqlDbType.NVarChar).Value = str;
using (SqlDataReader reader1 = oSqlCommand.ExecuteReader())
{
if (reader1.Read())
{
var findBusType = reader1["business_type"].ToString().Trim();
var selectedIndex = -1;
for (int i = 0; i < BusTypeddl.Items.Count; i++)
{
if (BusTypeddl.Items[i].ToString() == findBusType)
{
selectedIndex = i;
break;
}
}
if (selectedIndex > -1)
{
BusTypeddl.SelectedIndex = selectedIndex;
}
}
}
}
}
【问题讨论】:
-
findBusType列包含一个字符串,您需要在BusTypeddl中搜索此字符串。如果找到然后将其设置为选中,否则将选择默认值?这是你要找的吗? -
是的。 findBusType 只是我用来分配正确值的变量,一旦 reader1 在列中找到它。
-
它是 ASP.NET 所以项目是 ListItems 并且 ListItem 具有属性 Text,尝试使用 if (BusTypeddl.Items[i].Text.Trim() == findBusType)我>
标签: c# asp.net sql-server database