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
Related
I have created a search function that returns product data in a DataGridView (data is coming from local database), it does work but I need to have control over returned data in my grid view.
Current behavior
It returns all columns of database row in DataGridView
What I want
Returning only 2 or 3 columns of searched item instead of all columns
Create new list of searched items so I can edit those returned data
Logic
Search for product
Get product name and price from database, add custom quantity field make new list and add this item to show in DataGridView
Be able to change quantity field in DataGridView
Code
Here is my search code that returns all columns of product table
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (DataTable dt = new DataTable("Products"))
{
using (SqlCommand cmd = new SqlCommand("select * from Products where Id=#Id or Name like #Name", cn))
{
cmd.Parameters.AddWithValue("Id", searchBox.Text);
cmd.Parameters.AddWithValue("Name", string.Format("%{0}%", searchBox.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
// Following line will show all columns of founded product and replace it with next search result
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
selectedItems.DataSource = dt;
}
}
}
PS: Code above finds products based on id or name entered in search field and return all columns of product row.
Idea:
I think I can be able to create my list after finding product but the issue I'm facing is that I'm not sure how to get those specific columns from my dt (table row),
Here is what I've tried and failed (commented)
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"].ConnectionString))
{
if (cn.State == ConnectionState.Closed)
cn.Open();
using (DataTable dt = new DataTable("Products"))
{
using (SqlCommand cmd = new SqlCommand("select * from Products where Id=#Id or Name like #Name", cn))
{
cmd.Parameters.AddWithValue("Id", searchBox.Text);
cmd.Parameters.AddWithValue("Name", string.Format("%{0}%", searchBox.Text));
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
//selectedItems.DataSource = dt; //<-- changed with lines below
List<string> items = new List<string>();
items.Add(dt); // <-- here is the issue (it expect to get string of my table row let say: Price column, but I don't know how to get Price column value from dt)
selectedItems.DataSource = items;
}
}
}
PS: code above is just idea and obviously I am not sure if it is best way to do it or not that's why I'm asking here :)
Any suggestions?
Update
I've created new class and added my data to that class as following
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Price { get; set; }
public string Qty { get; set; }
}
Then in my query I added
List<Item> itemList = new List<Item>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Item item = new Item();
item.Id = Convert.ToInt32(dt.Rows[i]["Id"]);
item.Name = dt.Rows[i]["Name"].ToString();
item.Price = dt.Rows[i]["SellPrice"].ToString();
item.Qty = dt.Rows[i]["Qty"].ToString();
itemList.Add(item);
}
selectedItems.DataSource = itemList;
Now it does return data in my selectedItems but when I search for next product instead of adding it to the list it replace it with first product.
According to your sql query you are selecting all columns of the table.
To get the specific columns please change your sql query as such:
SqlCommand cmd = new SqlCommand("select Products.id, Products.name from Products where Id=#Id or Name like #Name", cn);
Thank you.
As per my understanding based on the comments, you are looking for some Linq code.
You only need to convert your result to a list that you could use.
Here is some code that might help you achieve this.
var result = dt.AsEnumerable().Select(x=> new {
Id = x["Id"],
Name = x["Name"],
Quantity = {Your Logic here}
});
selectedItems.DataSource = result;
You can then assign result to your datasource. You did not specify what your datasource is assigned to (selectedItems) so I do not know what type it is. but this should theoretically work. Just remove Quantity = {Your Logic here} from the code and see if it display's after which you could then just add it back and populate what you want Quantity to be
UPDATE
Because selectedItems is a DataGridView it requires a DataTable object to display the data. In which case you can not use an anonymous list as I created you would need something like this.
DataTable dtResult = new DataTable();
dtResult.Columns.Add("Id");
dtResult.Columns.Add("Name");
dtResult.Columns.Add("Quantity");
var result = dt.AsEnumerable().Select(x=> dtResult.Rows.Add(x["Id"],
x["Name"],
{Your Logic for Quantity here}
));
selectedItems.DataSource = result;
If you want to test this solution you can create a console application in c# and do something like where you can see the datasource is correct.
You could refer to the following code to show specific column data from database in winform datagirdview.
private void button1_Click(object sender, EventArgs e)
{
string str = "str";
SqlConnection connection = new SqlConnection(str);
connection.Open();
string sql = "select * from Product where Id=#Id or Name like #Name";
SqlCommand command = new SqlCommand(sql,connection);
command.Parameters.AddWithValue("#Id", textBox1.Text);
command.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
//Name=t.Field<string>("Name"), //The same way to show other columns data
Price = t.Field<string>("Price")
};
dataGridView1.DataSource = dt.ToList();
}
Result:
Database:
in C# and windows Form,
I have a database like this:
and this is how I using a class put it's data into a datagridview:
class DBConnection
{
public static void GetList(Form2 frm2)
{
string DBPath = Application.StartupPath;
OleDbConnection Connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+DBPath+#"\DataBase\SampleFeeds.accdb");
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary", Connection);
DataTable Dtable = new DataTable();
DataA.Fill(Dtable);
frm2.SelectedFeeddataGridView.DataSource = Dtable;
}
}
and this is my form load:
private void Form2_Load(object sender, EventArgs e)
{
DBConnection.GetList(this);
}
So far everything is ok.
now I have a question:
for example I have a list box FeedSelectListBox,
I want to when user click on a button GrassLegumeForagebtn my FeedSelectListBox fill with only all of Feed Names that are in the category of Grass / Legume Forage.
how should I do that ?
with help of Damirchi My problem solved
//-----------------
But now I have another question:
I want to when user select a feed from list box all of it's data from data base (like name, number, feed type and ,,,) put in a data grid view.
I used this code on my SelectFeedbtn but it doesn't work :
private void SelectFeedbtn_Click(object sender, EventArgs e)
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
string FeedSelectedID = FeedSelectListBox.SelectedValue.ToString();
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID = 'FeedSelectedID'" , Connection);
DataTable DTable = new DataTable();
DataA.Fill(DTable);
SelectedFeeddataGridView.DataSource = DTable;
}
And ValueMember property of FeedSelectListBox is ID but the error is :
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll.
I even use this query but it still doesn't work:
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID =" FeedSelectListBox.SelectedValue , Connection);
at first you most set the DisplayMember and ValueMember properties of FeedSelectListBox and use this code on click event.
you can put this code on GrassLegumeForagebtn click event.
string DBPath = Application.StartupPath;
OleDbConnection Connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+DBPath+#"\DataBase\SampleFeeds.accdb");
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where category='Grass / Legume'", Connection);
DataTable Dtable = new DataTable();
DataA.Fill(Dtable);
frm2.FeedSelectListBox .DataSource = Dtable;
(First of all I'm so sorry about my english, because I'm a stranger and I don't know well)
I'm working in a school project. But I need to set a DataTable as DataSource in ReportViewer. First the user type the ID of the Document, and click on the button, the button calls an class that do a select in my database and return 12 fields. I've created a DataSet with all fields that the select results and I've selected it as the Report DataSource. But I need to transfer the data of the select to the DataSet, because when I start my application the Report has an error. Here is the code, and I hope you can help me! Thanks.
Buttton Code:
SelectDocumento doc = new SelectDocumento();
doc.ImprimirDoc(int.Parse(txtID.Text));
Class that select data in my database:
public void ImprimirDoc(int id)
{
string pesquisar = "CALL SP_Imprimir_Documento(" + id + ")";
MySqlConnection con;
con = new MySqlConnection("Persist Security Info=false; server=localhost; database=hospital; uid=root; pwd=");
MySqlDataAdapter adapter = new MySqlDataAdapter(pesquisar, con);
DataTable dt = new DataTable();
dt.TableName = "DataSet1";
con.Open();
adapter.Fill(dt);
ImprimirDocumento imprimir = new ImprimirDocumento(dt);
imprimir.ShowDialog();
}
Code of the Report Form:
private DataTable proc;
public ImprimirDocumento(DataTable select)
{
InitializeComponent();
proc = select;
}
ConexaoHospital bd = new ConexaoHospital();
SelectDocumento doc = new SelectDocumento();
private void ImprimirDocumento_Load(object sender, EventArgs e)
{
this.rptDocumento.RefreshReport();
this.rptDocumento.LocalReport.DataSources.Clear();
Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", proc);
this.rptDocumento.LocalReport.DataSources.Add(rprtDTSource);
this.rptDocumento.RefreshReport();
}
Error that the Report Displays:
Error
If someone have a simmilar problem this way of my post is correct and my problem was because my ReportViewer DataSet name was different than my DataTable. My DataTable name was "DataSet1" and my DataSet name was "Documento". I changed the DataSet name for "DataSet1" and it works.
There are 2 columns, one with name and the other with email addresses. I want to be able to display the names from the name's column in a dropdown but user the email in the next column when the form is submitted on my asp page.
public void FillAssignedToDropdownOnsite()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["onsite_db"].ConnectionString);
string query = "SELECT Name, EmailAddress FROM OnsiteData ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
cmd.Connection.Open();
adpt.Fill(dt);
cmd.Connection.Close();
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataBind();
lstAssignedTo.Items.Insert(0, "Select Onsite Tech");
}
Sql table is OnsiteData
columns are name and emailaddress
Form has a dropdown that sends an email.
It seems that your tag is misplaced. Supposing that this is ASP.NET instead of ASP-Classic and lstAssignedTo is a DropDownList I suggest to use the DataValueField set to EmailAddress
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataValueField = "EMailAddress";
lstAssignedTo.DataBind();
when needed you could extract the email address for the selected user reading the Value property
if(lstAssignedTo.SelectedValue != null)
{
string email = lstAssignedTo.SelectedValue.ToString();
......
}
Not sure it's what you want :
lstAssignedTo.DataSource = dt;
lstAssignedTo.DataTextField = "Name";
lstAssignedTo.DataValueField = "EmailAddress"
lstAssignedTo.DataBind();
lstAssignedTo.Items.Insert(0, "Select Onsite Tech");
Like this the name is displayed and you can get the corresponding email with
var value = lstAssignedTo.SelectedValue;
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);