我在做实验室。我正努力在我的WebUserControl中将dropdownlist与SQL2008数据库绑定。当我的所有正面和背面代码都放在webusercontrol中时,实现它是一块蛋糕,但之后我被告知这种实现方式非常不专业。另外,有人告诉我,我需要构建一个包含私有变量和公共属性的中间类:
public class UsersIntoDLL
{
public UsersIntoDLL(int userID, string userName, string userFamilyName)
{
userID = UserID;
userName = UserName;
userFamilyName = UserFamilyName;
}
public int UserID
{ get; set; }
public string UserName
{ get; set; }
public string UserFamilyName
{ get; set; }
}
存储过程:
create procedure [dbo].[GetStudentsToDDL]
as
select UserID, UserName,UserFamilyName
from dbo.Users
新方法:
public List<UsersIntoDLL> GetStudents()
{
SqlConnection conn = new SqlConnection(Config.DbConnectionString);
SqlCommand cmd = new SqlCommand("GetStudentsToDDL", conn);
cmd.CommandType = CommandType.StoredProcedure;
List<UsersIntoDLL> udll = new List<UsersIntoDLL>();
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//ListItem lst = new ListItem();
//udll.Text = reader["StudentName"].ToString() + " " + reader["StudentFamilyname"].ToString();
UsersIntoDLL students = new UsersIntoDLL((int)reader["UserID"], (string)reader["UserName"],(string)reader["UserFamilyName"]);
udll.Add(students);
}
reader.Close();
}
catch (Exception ex)
{
// here should be some reference to label located in webusercontrol. don't know
// how to do it
Label err = new Label();
err.Text = ex.Message;
}
finally
{
conn.Close();
}
return udll;
}
webusercontrol的后台代码中的BadaBinding:
CatalogAccess ca = new CatalogAccess();
ddlStudents.DataSource = ca.GetStudents();
ddlStudents.DataTextField = "UserName";
ddlStudents.DataValueField = "UserID";
ddlStudents.DataBind();
我没有错误,没有约束力。学生不会出现在我的下拉列表中。请帮忙!!!
答案 0 :(得分:1)
啊,你没有正确设置你班级的变量。
请改用:
public class UsersIntoDLL {
public UsersIntoDLL(int userID, string userName, string userFamilyName)
{
UserID = userID;
UserName = userName;
UserFamilyName = userFamilyName;
}
public int UserID
{
get;
set;
}
public string UserName
{
get;
set;
}
public string UserFamilyName
{
get;
set;
}
}
答案 1 :(得分:0)
没有什么能立即跳出来,但您是否考虑过使用ObjectDataSource
(linky)
P.S。你检查过列表是不是空了?
答案 2 :(得分:0)
假设您在Visual Studio中运行此功能,是否可以在ddlStudents.DataSource = ca.GetStudents()
行设置断点并确保它不为空?
要排除其他潜在问题,请暂时将该行更改为:
ddlStudents.DataSource = new { UserName = "Test", UserID = "1" };
并查看下拉列表中是否显示至少一个项目。