使用C#和SQL通过组合框选择控制textBox的值 [英] Controlling the value of textBox by combobox selection using c# and sql

查看:70
本文介绍了使用C#和SQL通过组合框选择控制textBox的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过comboox选择来控制文本框的值.我的编码是:

I want to control the value of textbox through comboox selection.My coding is:

private void Form1_Load(object sender, EventArgs e)
       {
           SqlDataAdapter ad = new SqlDataAdapter("select *from Reg",con);
           DataSet ds = new DataSet();
           ad.Fill(ds, "Reg");
           comboBox1.DataSource = ds.Tables["Reg"].DefaultView;
           comboBox1.DisplayMember = "name";
           comboBox1.ValueMember = "name";

       }
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
       {
           SqlDataAdapter ad = new SqlDataAdapter("select *from Reg where name='" + comboBox1.SelectedItem.ToString()+ "'", con);
           DataSet ds = new DataSet();
           ad.Fill(ds, "Reg");
           dataGridView1.DataSource = ds.Tables["Reg"].DefaultView;
           textBox1.Text = ds.Tables["Reg"].Rows[0]["Email"].ToString();

       }



但是它显示了一个错误.该错误是:位置0没有行.

先生,请提供解决方案



But it is showing one error.That error is : There is no row at position 0.

Sir please give solution

推荐答案

http://social.msdn.microsoft.com/Forums/en/Vsexpressvb/thread/8844df20-9c56-47b5-8023-3d5b38d454d2[^]
I hope the above information will be helpful. If you have more concerns, please let me know.


您好,

请按如下所示更改您的代码.
Hi,

Please rechange the your code as follows.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  {
    SqlDataAdapter ad = new SqlDataAdapter("select *from Reg where name=''" + comboBox1.SelectedItem.ToString()+ "''", con);
     DataSet ds = new DataSet();
     ad.Fill(ds, "Reg");
     dataGridView1.DataSource = ds.Tables["Reg"].DefaultView;
     if(ds.Tables["Reg"].Rows.Count > 0)
       {
            textBox1.Text = ds.Tables["Reg"].Rows[0]["Email"].ToString();
       }
    else
      {
        textBox1.Text="";
      }
            
   }


如果数据库中没有所选的组合框值,它将返回零行.
这就是为什么出现这种错误的原因. 希望它能解决您的问题.

问候,
Kiran.


If the selected combo box value is not there in database,it will return zero rows.
Thats why you are getting this kind of error.
I hope it will solve your problem.

Regards,
Kiran.


我认为您应该使用
I think you should use
SqlDataAdapter ad = new SqlDataAdapter("select *from Reg where name=''" + comboBox1.SelectedValue.ToString()+ "''", con);

代替

SqlDataAdapter ad = new SqlDataAdapter("select *from Reg where name=''" + comboBox1.SelectedItem.ToString()+ "''", con);



希望对您有帮助,祝您好运!

爱德华



Hope it helps, Good luck!

Eduard


这篇关于使用C#和SQL通过组合框选择控制textBox的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆