首先,我想为我糟糕的标题道歉。
我正在使用 ASPNET Webforms 构建一个 CRUD 应用程序。我的一个页面包含一个下拉列表,其中填充了从 SQL 数据库中提取条目(Id、名字、姓氏)构建的字符串。
我想将下拉列表中的条目与数据库中项目的 ID 联系起来,以便我可以使用 then 进行更新和删除功能。
我目前有代码用这些 ID 填充一个列表,但后来我意识到我不知道如何将这些条目链接到 ID,或者甚至不知道如何链接这些 ID。
当前用于填充下拉菜单的代码:
// string for populating crud_dropDown
string commandString = "SELECT Id, FirstName, Surname FROM Users ORDER BY Id ASC;";
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
SqlDataReader myDataReader = sqlCmd.ExecuteReader();
// List to be populated with integers that correlate with with IDs in the database
List<int> DbIds = new List<int>();
while (myDataReader.Read())
{
// database IDs are are captured from database, saved as a string and converted to an integer
string listId = myDataReader["Id"].ToString();
int convtd_listId = Convert.ToInt32(listId);
// captured IDs are added to DbIds List
DbIds.Add(convtd_listId);
// crud_dropDown is populated with strings built with DbIds contents and names read from the database
string id = convtd_listId.ToString();
string fn = myDataReader["FirstName"].ToString();
string sn = myDataReader["Surname"].ToString();
crud_dropDown.Items.Add(id + " - " + fn + " - " + sn);
}
最佳答案
假设你暗示你正在从数据库中提取名称和 ID - 你正在创建一个包含信息的对象列表,所以你可以这样做:
创建一个类来保存详细信息,例如用户名和 ID 属性,以及它自己类型的列表(稍后的示例)。
然后在页面的代码隐藏中初始化对象并执行一些 sql 将数据库数据绑定(bind)到对象并将其读入列表:
User cUser = new User();
//From the sql:
while (reader.Read())
{
User u = new User
{
UserID = Convert.ToInt32(reader["UserID"]),
UsersName = reader["Name"].ToString()
};
cUser.lstUsers.Add(u);
}
//Now we have the data just pipe it into the dropdownlist:
foreach (User u in cUser.lstUsers)
{
//The dropdown control:
ddlUsers.Items.Add(new ListItem(u.UsersName, u.UserID.ToString()));
}
关于asp.net - 是否可以根据 C#/ASPNET Webforms 中选定的下拉项来定位数据库条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56479385/