- Remove From My Forums
-
Question
-
Hello,
In my form I have a combobox bound through a table adapter to a SQL Server stored proc. OnLoad the combobox initializes great, and I can select items from the dropdown that on SelectionChangeCommitted display in the combobox.text correctly, but the top item in the dropdown list (item 0) changes to the selected text and overwrites the first item.
After I use a button_Click procedure fill a second table adapter based on the combobox.text, selecting items in the combobox causes them to display only «System.Data.DataRowView» instead of the text that was there before. Nothing should be affecting the combobox, but something changes.
Me.GetTableAdapter1.Fill(Me.MyDataSet.MyStoredProc1)
Me
What am I missing? Thanks for any help you can provide.
Bruce.GetTableAdapter2.Fill(Me.MyDataSet.MyStoredProc2, Me.MyComboBox.Text)
Answers
-
You should bind it gracefully like following in the form load handler:
dim bs as BindingSource = new BindingSource(Me.MyDataSet, "MyStoredProc2"); Me.MyComboBox.DataSource = bs; Me.MyComboBox.DisplayMember = "yourDisplayMember"; Me.MyComboBox.ValueMember = "yourValueMember";
Please help us improve this community forum for visitors by marking the replies as answers if they help and unmarking them if they provide no help.
Thanks.-
Marked as answer by
Monday, February 22, 2010 2:23 AM
-
Marked as answer by
-
Don’t forget to also bind the SelectedValue to another table as well, or a new BindingSource from that other table if you prefer:
dim bs2 as BindingSource = new BindingSource(Me.MyDataSet.Tables(«OtherTable»))
Me.MyComboBox.DataBindings.Add(«SelectedValue», bs2, «MyOtherColumn»)
~~Bonnie Berent [C# MVP]
geek-goddess-bonnie.blogspot.com
-
Marked as answer by
Helen Zhou
Monday, February 22, 2010 2:24 AM
-
Marked as answer by
- Remove From My Forums
-
Question
-
Hello,
In my form I have a combobox bound through a table adapter to a SQL Server stored proc. OnLoad the combobox initializes great, and I can select items from the dropdown that on SelectionChangeCommitted display in the combobox.text correctly, but the top item in the dropdown list (item 0) changes to the selected text and overwrites the first item.
After I use a button_Click procedure fill a second table adapter based on the combobox.text, selecting items in the combobox causes them to display only «System.Data.DataRowView» instead of the text that was there before. Nothing should be affecting the combobox, but something changes.
Me.GetTableAdapter1.Fill(Me.MyDataSet.MyStoredProc1)
Me
What am I missing? Thanks for any help you can provide.
Bruce.GetTableAdapter2.Fill(Me.MyDataSet.MyStoredProc2, Me.MyComboBox.Text)
Answers
-
You should bind it gracefully like following in the form load handler:
dim bs as BindingSource = new BindingSource(Me.MyDataSet, "MyStoredProc2"); Me.MyComboBox.DataSource = bs; Me.MyComboBox.DisplayMember = "yourDisplayMember"; Me.MyComboBox.ValueMember = "yourValueMember";
Please help us improve this community forum for visitors by marking the replies as answers if they help and unmarking them if they provide no help.
Thanks.-
Marked as answer by
Monday, February 22, 2010 2:23 AM
-
Marked as answer by
-
Don’t forget to also bind the SelectedValue to another table as well, or a new BindingSource from that other table if you prefer:
dim bs2 as BindingSource = new BindingSource(Me.MyDataSet.Tables(«OtherTable»))
Me.MyComboBox.DataBindings.Add(«SelectedValue», bs2, «MyOtherColumn»)
~~Bonnie Berent [C# MVP]
geek-goddess-bonnie.blogspot.com
-
Marked as answer by
Helen Zhou
Monday, February 22, 2010 2:24 AM
-
Marked as answer by
- Remove From My Forums
-
Question
-
Hello,
In my form I have a combobox bound through a table adapter to a SQL Server stored proc. OnLoad the combobox initializes great, and I can select items from the dropdown that on SelectionChangeCommitted display in the combobox.text correctly, but the top item in the dropdown list (item 0) changes to the selected text and overwrites the first item.
After I use a button_Click procedure fill a second table adapter based on the combobox.text, selecting items in the combobox causes them to display only «System.Data.DataRowView» instead of the text that was there before. Nothing should be affecting the combobox, but something changes.
Me.GetTableAdapter1.Fill(Me.MyDataSet.MyStoredProc1)
Me
What am I missing? Thanks for any help you can provide.
Bruce.GetTableAdapter2.Fill(Me.MyDataSet.MyStoredProc2, Me.MyComboBox.Text)
Answers
-
You should bind it gracefully like following in the form load handler:
dim bs as BindingSource = new BindingSource(Me.MyDataSet, "MyStoredProc2"); Me.MyComboBox.DataSource = bs; Me.MyComboBox.DisplayMember = "yourDisplayMember"; Me.MyComboBox.ValueMember = "yourValueMember";
Please help us improve this community forum for visitors by marking the replies as answers if they help and unmarking them if they provide no help.
Thanks.-
Marked as answer by
Monday, February 22, 2010 2:23 AM
-
Marked as answer by
-
Don’t forget to also bind the SelectedValue to another table as well, or a new BindingSource from that other table if you prefer:
dim bs2 as BindingSource = new BindingSource(Me.MyDataSet.Tables(«OtherTable»))
Me.MyComboBox.DataBindings.Add(«SelectedValue», bs2, «MyOtherColumn»)
~~Bonnie Berent [C# MVP]
geek-goddess-bonnie.blogspot.com
-
Marked as answer by
Helen Zhou
Monday, February 22, 2010 2:24 AM
-
Marked as answer by
Heng 1 / 1 / 1 Регистрация: 02.10.2013 Сообщений: 96 |
||||||||
1 |
||||||||
04.04.2014, 18:41. Показов 3131. Ответов 2 Метки нет (Все метки)
Когда вывожу данные из бд в ListBox То в ListBox’е получаются строки типа: System.Data.DataRowView , а не название ячейки
Потом подправляю
и при копировании уже нужного названия из одного ListBox’а в другой опять строка типа: System.Data.DataRowView Добавлено через 48 минут
__________________
0 |
991 / 889 / 354 Регистрация: 24.03.2014 Сообщений: 2,381 Записей в блоге: 2 |
|
04.04.2014, 18:48 |
2 |
Копируете Вы, видимо, сам объект, который в общем-то в строке ListBox и лежит. Свойство DisplayMember отвечает за форматирование, т.е. ListBox ищет данное свойство на том объекте, что у него лежит в строке и показывает именно его. Определитесь сначала, что же Вам надо скопировать (а главное что потом с этим значением делать придётся).
0 |
1 / 1 / 1 Регистрация: 02.10.2013 Сообщений: 96 |
|
04.04.2014, 21:19 [ТС] |
3 |
Да точно, я решил просто в невидимый DGV закинуть и оттуда потом в StringList, можно было и оптимальней подумать , но пока так устраивает.
0 |
See more:
Hello,
I m using a combobox in my window’s application.
And the combobox is bind with datasource using valuemember and displaymember.
and on selectedindexchenged of combobox i m trying to fill my datagridview.
and i m doing this through the combobox.selectedvalue.
But i always got an error that the datatype is not valid for boolean operation.
[Data type(if known)=int,data type(if known)=nvarchar]
and my datagridview does not fill.
private void Form_Load(object sender, EventArgs e) { try { label3.Visible = false; label4.Visible = false; string connstring = Properties.Settings.Default.TestDBConnectionString; con = new SqlCeConnection(connstring); con.Open(); getallsubject(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void getallsubject() { try { da = new SqlCeDataAdapter("select SubjectId,SubjectName from Subject", con); DataTable dt = new DataTable(); da.Fill(dt); if (dt != null) { comboBoxsubject.DataSource = dt; comboBoxsubject.ValueMember = dt.Columns[0].ToString(); comboBoxsubject.DisplayMember = dt.Columns[1].ToString(); } else { MessageBox.Show("No subject to add unit.Before proceed add subjects."); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void comboBoxsubject_SelectedValueChanged(object sender, EventArgs e) { getallunit(); }
private void getallunit() { try { if (comboBoxsubject.SelectedValue!="0") { da = new SqlCeDataAdapter("select u.UnitId,u.UnitName,s.SubjectName from SubjectUnit u,Subject s where u.SubjectId=s.SubjectId and u.SubjectId='" +comboBoxsubject.SelectedValue + "'", con); DataTable dt = new DataTable(); da.Fill(dt); if (dt != null) { dataGridViewunit.DataSource = dt; } else { MessageBox.Show("No units has been added yet."); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
I would suggest you to change the order
comboBoxsubject.ValueMember = dt.Columns[0].ToString(); comboBoxsubject.DisplayMember = dt.Columns[1].ToString(); comboBoxsubject.DataSource = dt;
I was having the same problem and tried
dt.Columns[0].ToString();
which worked fine! After some inspection I came to the conclusion that this problem has to do with regional settings, since it works everywhere else except one client that has different regional settings (Turkey in my case).
Try this in your Dataadapter
da = new SqlCeDataAdapter("select u.UnitId,u.UnitName,s.SubjectName from SubjectUnit u,Subject s where u.SubjectId=s.SubjectId and s.SubjectId='" +comboBoxsubject.SelectedValue + "'", con) OR da = new SqlCeDataAdapter("select u.UnitId,u.UnitName,s.SubjectName from SubjectUnit u,Subject s where s.SubjectId='" +comboBoxsubject.SelectedValue + "'", con); ;
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
В моем коде я сделал метод для каждой кнопки, в качестве примера у меня есть кнопки курицы и говядины, и у них есть свои собственные методы, когда я нажимаю кнопку курицы в первый раз, когда загруженная форма работает, она будет отображаться в списке. но когда я нажимаю кнопку говядины после курицы, это показывает мне System.ArgumentException. Как бы это исправить?
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.ValueMember = "Chicken_ID";
lst_SHowdata.ValueMember = "Beef_ID";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
}
}
private void Beef()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Beef_Name,WithOrWithout_Name ,Beef_Price from Tbl_Add a full outer join Tbl_Beef b ON b.Beef_ID = a.Beef_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Beef = new DataTable();
adapter.Fill(tbl_Beef);
lst_SHowdata.DisplayMember = "Beef_Name";
lstSHowdata2.DisplayMember = "Beef_Price";
lst_SHowdata.ValueMember = "Beef_ID";
lst_SHowdata.ValueMember = "Chicken_ID";
lst_SHowdata.DataSource = tbl_Beef;
lstSHowdata2.DataSource = tbl_Beef;
}
}
private void button1_Click(object sender, EventArgs e)
{
Chicken();
}
private void button2_Click(object sender, EventArgs e)
{
Beef();
}
И я попытался это исправить, сделав комментарий для строк, которые делают исключение
//lst_SHowdata.ValueMember = "Chicken_ID";
// lst_SHowdata.ValueMember = "Beef_ID";
И вроде как было исправлено, но мне нужно дважды нажать кнопку, когда я нажимаю ее в первый раз, она будет отображаться в списке System.Data.DataRowView . как это исправить и сделать так, чтобы он отображался только при первом нажатии?
4 ответа
Лучший ответ
Поправьте меня если я ошибаюсь. Вот как это понять. Вы пытаетесь привязать данные к списку при нажатии кнопки. У вас есть 2 элемента управления списка для привязки.
Сначала назначьте источник данных, прежде чем назначать участников. Он не может связываться, потому что ему еще не предоставлен источник данных.
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
connection.Open(); //opens the connection
adapter.Fill(tbl_Chicken);
connection.Close(); //Closes the connection
lst_SHowdata.DataSource = tbl_Chicken; //assigns a datasource
lst_SHowdata.DisplayMember = "Chicken_Name"; //assigns display
lst_SHowdata.ValueMember = "Chicken_ID"; //assigns id
lst_SHowdata2.DataSource = tbl_Chicken;
lst_SHowdata2.DisplayMember ="Chicken_Price";
lst_SHowdata2.ValueMember = "Chicken_ID";
}
}
private void Beef()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Beef_Name,WithOrWithout_Name ,Beef_Price from Tbl_Add a full outer join Tbl_Beef b ON b.Beef_ID = a.Beef_ID full outer join Tbl_WithORWithout c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Beef = new DataTable();
connection.Open();
adapter.Fill(tbl_Beef);
connection.Close();
lst_SHowdata.DataSource = tbl_Beef
lst_SHowdata.DisplayMember = "Beef_Name";
lst_SHowdata.ValueMember = "Beef_ID";
lst_SHowdata2.DataSource = tbl_Beef;
lst_SHowdata2.ValueMember = "Beef_ID";
lst_SHowdata2.DisplayMember = "Beef_Price";
}
}
0
jmag
10 Мар 2017 в 13:18
Вы получаете сообщение об ошибке, потому что, когда вы пытаетесь установить ValueMember на «Bee_Name», список привязывается к tbl_chicken, в котором нет Beef_Name, и поэтому он — правильно — жалуется.
Чтобы обойти это, установите Источники данных в tbl_beef, а затем установите ValueMember.
0
simon at rcl
7 Мар 2017 в 17:29
Правильный код ^^ это
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select * from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
connection.Open(); //opens the connection
adapter.Fill(tbl_Chicken);
connection.Close(); //Closes the connection
lst_Menu.DataSource = tbl_Chicken; //assigns a datasource
lst_Menu.DisplayMember = "Chicken_Name"; //assigns display
lst_Menu.ValueMember = "Chicken_Name";
lst_worwout.DataSource = tbl_Chicken;
lst_worwout.DisplayMember = "WithOrWithout_Name";
lst_worwout.ValueMember = "WithOrWithout_Name";
lst_Price.DataSource = tbl_Chicken;
lst_Price.DisplayMember = "Chicken_Price";
lst_Price.ValueMember = "Chicken_Price";
}
}
0
Max Saeed
10 Окт 2017 в 18:33
Ошибка заключается в том, что значениеМембер — это «Beef_ID» и «Chicken_ID». Они не доступны в Dataatable. Вам нужно изменить его на «Beef_Name» или включить «Beef_ID» в оператор выбора sql. Также для одного и того же списка вы устанавливаете два разных значения Member.
0
BipinR
7 Мар 2017 в 17:40