Sar*_*shi 6 c# sql-server data-binding combobox
我将组合框与数据源,displaymember,valuemember绑定。它在我的计算机上可以正常工作,但在客户端PC上却无法工作。以下是我的源代码:
从UserControl的构造方法中调用cbxAlloyBinding方法。
private void cbxAlloyBinding()
{
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("SELECT alloyName,alloyId FROM alloy", con);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
cbxMetal.DisplayMember = "alloyName";
cbxMetal.ValueMember = "alloyId";
cbxMetal.DataSource = dt;
}
else
{
cbxMetal.Text = "";
}
}
private void cbxMetal_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbxMetal.SelectedIndex != -1)
{
DataTable dt = new DataTable();
tempcmd = new SqlCommand("SELECT specification,alloyCode FROM alloy where alloyId='" + cbxMetal.SelectedValue + "'", con);
SqlDataAdapter adp = new SqlDataAdapter(tempcmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
txtSpecification.Text = dt.Rows[0]["alloyCode"].ToString();
txtSupplyConditions.Text = dt.Rows[0]["specification"].ToString();
cbxheatBinding();
}
else
{
txtSpecification.Text = "";
}
}
}
Run Code Online (Sandbox Code Playgroud)
最近两天这让我很困扰,我几乎尝试了所有技巧,但仍然无法正常工作。
客户的PC正在使用Windows 7 Ultimate,SQL Server 2005和.net Framework 3.5。
如果在构造函数中cbxMetal_SelectedIndexChanged调用了before,cbxAlloyBinding()则肯定会发生这种情况。
例如(请参见下面的代码),您可能在构造函数中具有其他组合框绑定cbxAlloyBinding(),而这些组合框绑定可能早于构造函数,并且这些绑定正在调用cbxMetal_SelectedIndexChanged。
public Constructor()
{
InitializeComponent();
cbxheatBinding(); //1st Three Binding Methods may be somehow related to your cbxMetal,
dtpStartDateBinding(); //which leads them to call cbxMetal_SelectedIndexChanged method.
dtpEndDateBinding();
cbxAlloyBinding();
}
Run Code Online (Sandbox Code Playgroud)
我怀疑您cbxMetal.DataSource是从代码中的其他位置开始设置的,并且早于DisplayMember并被ValueMember分配了;
请记住,System.DataRow.DataRowView只有在
ComboBox.SelectedValue在ValueMember分配之前被调用。
设置DisplayMember和ValueMemeber设置后的DataSource修复了这个问题对我来说。
cbxMetal.DataSource = dt;
cbxMetal.DisplayMember = "alloyName";
cbxMetal.ValueMember = "alloyId";
Run Code Online (Sandbox Code Playgroud)
问题似乎不在于您在此处粘贴的代码,可能与客户端环境、连接、权限等有关。您必须提供有关“它在客户端电脑中无法工作”的更多信息。他们使用什么系统,错误是什么,你尝试过在客户端调试吗?
*编辑: *那么你必须从头开始跟踪所有操作来找到问题。我的建议是制作一个虚拟的 Windows 窗体应用程序,只需一个标准窗体、一个组合框和一个按钮。在按钮的单击事件上,只需执行您所做的操作即可。只需绑定组合并将此临时应用程序发送到客户端即可。如果有效,则逐步执行。例如:
private void button1_Click(object sender, EventArgs e)
{
string conStr = "Data Source=PC-303\\SQLEXPRESS;Initial Catalog=sokaklar;User ID=sa;Password=*****";
SqlDataAdapter adapter = new SqlDataAdapter("SELECT DISTINCT IL, IL_ID FROM sokaklar ORDER BY IL", new SqlConnection(conStr));
DataTable dt = new System.Data.DataTable();
adapter.Fill(dt);
comboBox1.DisplayMember = "IL";
comboBox1.ValueMember = "IL_ID";
comboBox1.DataSource = dt;
}
Run Code Online (Sandbox Code Playgroud)
我在一分钟内创建了这个应用程序,它对我有用。