[英]Programmatically Binding ComboBox(s) By Control Name
Let me preface this by saying I don't do very much winforms work so pardon my ignorance. 首先,请允许我说我做的Winforms很少,所以请原谅我的无知。 Binding is slightly strange coming from ASP.
绑定来自ASP有点奇怪。
I'm trying loop over a series of combo boxes and bind them using a dictionary of control names and a corresponding stored procedure. 我正在尝试遍历一系列组合框,并使用控件名称字典和相应的存储过程将它们绑定。 Here is a simplified example of what I'm trying to do.
这是我要执行的操作的简化示例。
public Dictionary<string, string> GetDropDownSchema()
{
return new Dictionary<string, string> { {"ddClient", "guisp_SelectClientDropDown"}, {"ddType", "guisp_SelectTypeDropDown"}, {"ddCounty", "guisp_SelectCountyDropDown"}};
}
public void BindComboBoxes()
{
var ddSchem = GetDropDownSchema();
foreach (var dd in ddSchem) {
var dt = new DataTable();
using (var con = new SqlConnection(ConStr)) {
try {
var adapter = new SqlDataAdapter(dd.Value, con);
adapter.Fill(dt);
((ComboBox)Controls.Find(dd.Key, true)[0]).DataSource = dt;
((ComboBox)Controls.Find(dd.Key, true)[0]).DisplayMember = "DisplayText";
((ComboBox)Controls.Find(dd.Key, true)[0]).ValueMember = "ID";
}
catch //(Exception ex)
{
//Code is not throwing any exception, just doesn't work
}
}
}
I'm sure I'm missing something simple with this. 我敢肯定我缺少这种简单的东西。 I appreciate any help or suggestion on a more elegant way to go about this.
感谢您提供的帮助或建议,以一种更优雅的方式解决此问题。
Thanks 谢谢
I suppose that the guisp_XXXXXX are names of stored procedures. 我想guisp_XXXXXX是存储过程的名称。 If this is the case then you cannot use them in that way to fill a datatable using a SqlDataAdapter.
如果是这种情况,则您不能以这种方式使用它们来通过SqlDataAdapter填充数据表。
Instead you need to build a SqlCommand, specify that its CommandType is StoredProcedure and assign that command to the SelectCommand property of the SqlDataAdapter 相反,您需要构建一个SqlCommand,将其CommandType指定为StoredProcedure,然后将该命令分配给SqlDataAdapter的SelectCommand属性。
using (var con = new SqlConnection(ConStr))
{
try
{
con.Open();
var adapter = new SqlDataAdapter();
var cmd = new SqlCommand(dd.Value, con);
cmd.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand = cmd;
adapter.Fill(dt);
......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.