Combobox databinding showing system.data.datarowview - c#

I am binding combobox with datasource, displaymember, valuemember. It is working fine in my computer but it is not working in clients pc. Following is my source code:
cbxAlloyBinding method is called from the Constructor of the UserControl.
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 = "";
}
}
}
This is bothering me from last two days and i almost tried all tricks but it is still not working.
Client's PC is using Windows 7 ultimate, sql server 2005 and .net framework 3.5.

This definitely happens if your cbxMetal_SelectedIndexChanged is called before cbxAlloyBinding() is called in your constructor.
For instance (see the code below), you may have other combobox bindings in constructor which may come before cbxAlloyBinding() in constructor, and those bindings are calling 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();
}
What I suspect is your cbxMetal.DataSource is set from some other point in your code and well before DisplayMember and ValueMember are assigned;
Just remember, System.DataRow.DataRowView will occur only if
ComboBox.SelectedValue is called before ValueMember assignment.

setting the DisplayMember and ValueMemeber after setting the DataSource fixed this issue for me.
cbxMetal.DataSource = dt;
cbxMetal.DisplayMember = "alloyName";
cbxMetal.ValueMember = "alloyId";

It seems problem is not with the code you pasted here, it may be with client environment, connection, privileges etc. You must give more info about that 'it is not working in clients pc'. What systems they use, what is the error, have you tried debugging in client side?
*Edit:*then you have to find the problem tracing all the operation from the beginning. My advice is that make a dummy windows form application, just a standard form, a combobox and a button. ON the click event of button just do what you did. JUst bind the combo and send this temp app to the client. If it works then do step by step.Ex:
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;
}
I created this app in one minute, and it is working for me.

I resolved same this:
/*First get DataSource*/
comboBox1.DataSource = dt;
/*Then determine DisplayMember y ValueMember*/
comboBox1.DisplayMember = "YOUR_FIELD_NAME";
comboBox1.ValueMember = "YOUR_OTHER_FIELD_NAME";
This only works with
System.Data.DataTable
or
List
data sources

It was showing me the same exception, so I did this and it worked
private void cb_category_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable mydt = new DataTable();
try
{
mydt = request.GetItem(int.Parse(cb_category.SelectedValue.ToString()));
}
catch { }
if(mydt.Rows.Count>0)
{
cb_Item.DataSource = mydt;
cb_Item.DisplayMember = "dispmember";
cb_Item.ValueMember = "valmember";
}
else
{
cb_Item.DataSource = null;
}
}

THIS WILL DEFINITELY HELP TO YOU
on the load Event you want to Just Write this code
onformload()
{
cmb_dept.Items.Clear();
SqlConnection conn = new SqlConnection(#"DATA SOURCE=(localdb)\MSSQLLocalDB;INTEGRATED SECURITY=true;INITIAL CATALOG=EMPLOYEE;");
conn.Open();
SqlCommand command = new SqlCommand("select dept_id, dept_name from department", conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
cmb_dept.ValueMember = "dept_id";
cmb_dept.DisplayMember = "dept_name";
cmb_dept.DataSource = ds.Tables[0];
}
try using Use the code where you want to access the values........
string dept = cmb_dept.Text;
MessageBox.Show("val=" + dept);
YOUR combobox.text = System.Data.DataRowView Will be Solved ##

reading the answer in this post tells me there are so many ways this bug can reveal itself, for me it was the following: I had the combobox bound exact like mentioned in the question, and it was working fine, I change the Sorted property of the combobox to True in the Designer and started getting datarowview thing in each item. After wasting a lot of time found out that Sorted property should be False for this to work as expected. Sorting has to be dont through the query you used to get the data.

"comboBox1.SelectedValue" returns object and you want as string so convert it Convert.ToString(comboBox1.SelectedValue) and then use
for example:
tempcmd = new SqlCommand("SELECT specification,alloyCode FROM alloy where alloyId='" + Convert.ToString(cbxMetal.SelectedValue) + "'", con);

Related

ComboBox doesn't show the data

ComboBox doesn't show the data, I populate my combobox with data from my database this way:
private void PartDefective(string id)
{
cmd = new SQLiteCommand("Select * FROM Part_defective where testers = '" + id + "'", DBcon);
if (DBcon.State == ConnectionState.Closed)
DBcon.Open();
myDA = new SQLiteDataAdapter(cmd);
myDataSet = new DataSet();
myDA.Fill(myDataSet, "comboBox6");
this.comboBox6.DataSource = myDataSet.Tables["comboBox6"].DefaultView;
this.comboBox6.ValueMember = "Part";
this.comboBox6.DisplayMember = "Part";
this.comboBox6.SelectedItem = "ID";
this.comboBox6.SelectedIndex = -1;
DBcon.Close();
}
And to show the data from the database I used :
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.comboBox6.SelectedValue == null)
{
testerid = "1";
}
else
{
part = this.comboBox6.SelectedText.ToString();
}
}
There is absolutely no reason to define the SelectedItem or SelectedIndex.
The SelectedIndexChanged Event is also completely redundant for displaying your combobox.
Remove these lines and see if it solved your problem.
this.comboBox6.SelectedItem = "ID";
this.comboBox6.SelectedIndex = -1;
If the combobox is still empty, the root of problem has to be with the fetching of your data and filling the datasource.
Put a breakpoint on this line:
this.comboBox6.DataSource = myDataSet.Tables["comboBox6"].DefaultView;
And then look at the value of myDataSet.Tables["comboBox6"] in the watch or quickwatch window. Are there any rows?
Also change your code:
string sql = "Select * FROM Part_defective where testers = '" + id + "'";
cmd = new SQLiteCommand(sql, DBcon);
Put a breakpoint there, see what the value of sql is.
Manually run the sql against your database and see if there are any results.

No mapping exists from object type System.Data.DataRowView?

I have this code
private void cmb_public_manag_SelectedIndexChanged(object sender, EventArgs e)
{
//DB_Mange.fill_combox_Exchange("[Public_administration_dept]", cmb_public_manag_dept, "dept_id", "dept_name", cmb_public_manag.SelectedValue, "");
using (SqlConnection con = new SqlConnection(SQL_DB.con_str))
{
con.Open();
using (SqlCommand scm = new SqlCommand())
{
scm.Connection = con;
scm.CommandText = "select * from Public_administration_dept where Public_administration_id=#dept_id";
scm.Parameters.AddWithValue("#dept_id",cmb_public_manag.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter();
adpt.SelectCommand = scm;
adpt.Fill(dt);
cmb_public_manag_dept.DisplayMember = dt.Columns["dept_name"].ToString();
cmb_public_manag_dept.ValueMember = dt.Columns["dept_id"].ToString();
cmb_public_manag_dept.DataSource = dt;
}
}
}
always showing me this error
No mapping exists from object type System.Data.DataRowView to a known
managed provider native type.
this code SelectedIndexChanged
I guess the exception is raised at
scm.Parameters.AddWithValue("#dept_id",cmb_public_manag.SelectedValue);
and that cmb_public_manag.SelectedValue is not an int but a DataRowView. Then use:
int dept_id = ((DataRowView) cmb_public_manag.SelectedValue).Row.Field<int>("dept_id");
scm.Parameters.AddWithValue("#dept_id", dept_id );
The reason for cmb_public_manag.SelectedValue being a DataRowView instead of an int is the order of assignment.
Always provide the DataSource as the last step since that can cause events in winforms. In these events the DisplayMember and ValueMember are not yet assigned. In this case the code is sitting in the SelectedIndexChanged of the ComboBox that you are currently assigning the DataSource, so the method calls itself. But because you have assigned the DataSource first the ValueMember is unassigned and the whole object is returned from SelectedValue.
So instead use this:
cmb_public_manag_dept.SelectedIndexChanged -= cmb_public_manag_SelectedIndexChanged;
cmb_public_manag_dept.DisplayMember = "dept_name";
cmb_public_manag_dept.ValueMember = "dept_id";
cmb_public_manag_dept.DataSource = dt;
cmb_public_manag_dept.SelectedIndexChanged += cmb_public_manag_SelectedIndexChanged;
Note that you should also unsubscribe from this event when you change the datasource in it.
Also note that i've changed dt.Columns["dept_name"].ToString() to simply "dept_name" which is the same.

Filling a DataTable in C# using MySQL

I'm attempting to fill a DataTable with results pulled from a MySQL database, however the DataTable, although it is initialised, doesn't populate. I wanted to use this DataTable to fill a ListView. Here's what I've got for the setting of the DataTable:
public DataTable SelectCharacters(string loginName)
{
this.Initialise();
string connection = "0.0.0.0";
string query = "SELECT * FROM characters WHERE _SteamName = '" + loginName + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
}
else
{
this.CloseConnection();
DataTable dt = new DataTable("CharacterInfo");
return dt;
}
}
And for the filling of the ListView, I've got:
private void button1_Click(object sender, EventArgs e)
{
string searchCriteria = textBox1.Text;
dt = characterDatabase.SelectCharacters(searchCriteria);
MessageBox.Show(dt.ToString());
listView1.View = View.Details;
ListViewItem iItem;
foreach (DataRow row in dt.Rows)
{
iItem = new ListViewItem();
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i == 0)
iItem.Text = row.ItemArray[i].ToString();
else
iItem.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(iItem);
}
}
Is there something I'm missing? The MessageBox was included so I could see if it has populated, to no luck.
Thanks for any help you can give.
Check your connection string and instead of using
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
you can use this one
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
dt.load(cmd.ExecuteReader());
return dt;
Well, I ... can't figure out what you have done here so I'll paste you my code with which I'm filling datagridview:
1) Connection should look something like this(if localhost is your server, else, IP adress of server machine):
string connection = #"server=localhost;uid=root;password=*******;database=*******;port=3306;charset=utf8";
2) Query is ok(it will return you something), but you shouldn't build SQL statements like that.. use parameters instead. See SQL injection.
3) Code:
void SelectAllFrom(string query, DataGridView dgv)
{
_dataTable.Clear();
try
{
_conn = new MySqlConnection(connection);
_conn.Open();
_cmd = new MySqlCommand
{
Connection = _conn,
CommandText = query
};
_cmd.ExecuteNonQuery();
_da = new MySqlDataAdapter(_cmd);
_da.Fill(_dataTable);
_cb = new MySqlCommandBuilder(_da);
dgv.DataSource = _dataTable;
dgv.DataMember = _dataTable.TableName;
dgv.AutoResizeColumns();
_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (_conn != null) _conn.Close();
}
}
So, every time I want to display some content of table in mysql database I call this method, pass query string and datagridview name to that method. and, that is it.
For your sake, compare this example with your and see what can you use from both of it. Maybe, listview is not the best thing for you, just saying ...
hope that this will help you a little bit.
Debug your application and see if your sql statement/ connection string is correct and returns some value, also verify if your application is not throwing any exception.
Your connection string is invalid.
Set it as follows:
connection = "Server=myServer;Database=myDataBase;Uid=myUser;Pwd=myPassword;";
Refer: mysql connection strings
Here the following why the codes would not work.
Connection
The connection of your mySQL is invalid
Query
I guess do you want to search in the table, try this query
string query = "SELECT * FROM characters WHERE _SteamName LIKE '" + loginName + "%'";
notice the LIKE and % this could help to list all the data. for more details String Comparison Functions

OleDbDataAdapter: cannot update database

I've been working on this since yesterday and I just can't update my database.
There are 3 tables. Here is a piece of code of one of WinForms. It loads data and display but after changing sth manually in the grid I get either errors by calling Update or anything happens at all.
please help because I'm going crazy.
public partial class Form3 : Form
{
//instance fields
private export2Excel export2XLS;
private DataSet _dataSet;
private BindingSource _bsrc;
private OleDbDataAdapter _dAdapter;
private OleDbCommandBuilder _cBuilder;
private DataTable _dTable;
private void button1_Click(object sender, EventArgs e)
{
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source='C:\\Documents and Settings\\dorota\\Moje dokumenty\\Visual Studio
2010\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\artb.mdb'";
//create the database query
string query = "SELECT * FROM Samochody";
System.Data.DataSet DtSet = new System.Data.DataSet();
_dataSet = DtSet;
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
dAdapter.FillSchema(_dataSet, SchemaType.Source);
_dAdapter = dAdapter;
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(_dAdapter);
_cBuilder = cBuilder;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
_dTable = dTable;
//fill the DataTable
_dAdapter.Fill(_dTable);
//_dAdapter.TableMappings.Add("Samochody", "Table");
_dAdapter.Fill(_dataSet);
// --------------------- to datagridview !
//BindingSource to sync DataTable and DataGridView
BindingSource _bsrc = new BindingSource();
//set the BindingSource DataSource
//bSource.DataSource = _dTable;
_bsrc.DataSource = _dTable;
//_bsrc = bSource;
//set the DataGridView DataSource
dataGridView1.DataSource = _bsrc;
}
}
and here... :
private void sqlsave_Click(object sender, EventArgs e)
{
//int i=_dAdapter.Update(_dTable);
_dAdapter.Update(_dataSet.Tables["Samochody"]);
//_dAdapter.Update(_dataSet,"Samochody");
}
//---------------------------------------------------------------------------------
ok. I have changed sqlsave method for this
private void sqlsave_Click(object sender, EventArgs e)
{
try
{
//_dAdapter.Update(_dataSet.Tables["Samochody"]);
OleDbCommand oldb= _cBuilder.GetUpdateCommand();
int i=oldb.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show(i+" rows affected.");
//_dAdapter.Update(_dataSet,"Samochody");
}catch(OleDbException oldbex){
System.Windows.Forms.MessageBox.Show(oldbex.ToString());
}
and now I get finally sth more informative than "Error in"
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll Additional information: ExecuteNonQuery
requires an open and available Connection. The connection's current
state is closed.
so let me changed sth and I will let you know if this is it!
//--------------------------------
no. no. too fast, can't last. now while trying to save I've got exception again,
connectin is opened, but (I can't post the image) when I debug this I see that my object of OleDbCommand type as _commandText has
"UPDATE Samochody SET Item=?, Data dyspozycji autem od=?, ..."
and so on.
I think this is the reason. Am I right? What to do?
You didn't provide a connection for your OleDbDataAdapter. Try it something like this:
The example is different from your code but it shows the declaration of New Connection and passing it to the OleDbDataAdapter
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter ;
OleDbCommandBuilder oledbCmdBuilder ;
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
sql = "select * from tblUsers";
try
{
connection.Open(); // your code must have like this
oledbAdapter = new OleDbDataAdapter(sql, connection);
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ds.Tables[0].Rows[i].ItemArray[2] = "neweamil#email.com";
}
oledbAdapter.Update(ds.Tables[0]);
connection.Close();
MessageBox.Show ("Email address updates !");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I've found the answer:
But a better approach would be to use drag-and-drop and learn form the code.
Select Data|View Datasources. Your dataset should be visible in the DataSources Window.
Drag a table to a (new) form. VS2005 will add a load of components and a few lines of code.
The form will now have a instance of the dataset and that is your reference point for Adapter.Fill and .Update methods.
Easy and works great! : D
I've found it here: https://stackoverflow.com/a/548124/1141471

Bind combobox with data from database

I had windows form and I added combobox which bin data from database I added my code but this error apeared (invalid column name Category) altought the name was right .
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category,Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}
Change your query like this,
Select Category.Category as CatName ,Category.Id from Category
i-e use an alias like "CatName" for your column and set Display member like this,
CBParent.DisplayMember = "CatName";
Hope it shall help.
I checked the connection and I found the connectionstring was wrong

Categories

Resources