开发者

error in connecting combox to textbox with database

开发者 https://www.devze.com 2023-01-07 00:43 出处:网络
i am working on C# .net platform i wanted to connect my combox to my text box this is code done by me but it is give me error

i am working on C# .net platform

i wanted to connect my combox to my text box

this is code done by me but it is give me error

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            panel1.Visible = true;
            string sql;
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = "Data Source=CJ\SQLEXPRESS;Initial Catalog=elligiblity;Persist Security Info=True;User ID=sa;Password=123";
            cn.Open();
            sql = "SELECT inst_name FROM institude WHERE(inst_id="+comboBox2.SelectedItem+")";
            SqlCommand cmd = new SqlCommand(sql,cn);
            SqlDataReader myReade开发者_JAVA技巧r = cmd.ExecuteReader();
            while(myReader.Read())
            {
                   textBox2.Text = myReader["inst_name"].ToString();
            }
            myReader.Close();
            cn.Close();

The multi-part identifier "System.Data.DataRowView" could not be bound.

on this line of the code

SqlDataReader myReader = cmd.ExecuteReader();


As well as that problem there are a few issues with your code that you might want to bear in mind.

Firstly, if there is an error between opening and closing the connection (as indeed there was) then you're probably going to leave connections open. Eventually this will choke your site. Use

using (SqlConnection cn = new SqlConnection())
{

}

when you're out of the scope of the using statement the connection will be closed and disposed of.

Also, you probably want to parameterize your query (for reasons both of security and efficiency), so that it is

sql = "SELECT inst_name FROM institude WHERE(inst_id=@inst_id)";

Then add that parameter to your command object and set its value to your combo box selected item value.


You want

comboBox2.SelectedValue

or

comboxBox2.SelectedItem.ToString()

then but I'd look at using parameters instead as that's not a very good way of creating a SQL string.

Also, do you realise that if you return more than one result your textbox2 will only show the last result as its text will get over-ridden with each result as its read?


First of all check the binding of dropdown. If you are binding datasource with ID and Text something like this combobox2.DisplayMember ="Name"; combobox2.ValueMember ="ID". After that you have to check for the parameter to be used in your query if its text then try combobox2.text else if you are selecting on the basis of id use int.parse(combobox2.selectedvalue) or simply combobox2.selectedvalue if your id is alphanumeric.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号