Populating combobox with MS Access Data in C# - c#

Is it possible to populate a combobox in c# with data from a datagridview which is linked to a Microsoft Access database & if not an existing record populate it with a selection based on the access dataview lookup data selections. I would like to be able to populate all of the text boxes & combo boxes if i select the record in the datagridview & if it is not yet a record i want to be able to select an option from the Combo Box pulldown in order to save the data to the database. I also want the datagrid to start with the first id which i think i have to do with the sql statement & i also do not want duplicate items in the pull down as you see in my state selection Combo Box. This Combo Box is based on the column data so all of the different records with the same data shows up in the Combo Box. Here is a bit of the code:
private void WendysForm_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
// + values('" txt_ID.Text + "', ' "txt_Nickname.Text + '")
string query =
"select * from Wendys";
command.CommandText = query;
OleDbDataReader reader= command.ExecuteReader();
while(reader.Read())
{
cb_State.Items.Add(reader["State"].ToString());
cb_AssetType.Items.Add(reader["AssetType"].ToString());
cb_BaseModel.Items.Add(reader["BaseModel"].ToString());
cb_BldgPrototypeYear.Items.Add(reader["BldgPrototypeYear"].ToString());
cb_UpgradeClass.Items.Add(reader["UpgradeClass"].ToString());
cb_ExtWallStructure.Items.Add(reader["ExtWallStructure"].ToString());
cb_NewWallStructure.Items.Add(reader["NewWallStructure"].ToString());
cb_ExtRoofStructure.Items.Add(reader["ExtRoofStructure"].ToString());
cb_NewRoofStructure.Items.Add(reader["NewRoofStructure"].ToString());
cb_ExtFndType.Items.Add(reader["ExstFoundationType"].ToString());
cb_NewFndType.Items.Add(reader["NewFoundationType"].ToString());
cb_Addition.Items.Add(reader["Addition"].ToString());
cb_BladeDesign.Items.Add(reader["BladeDesign"].ToString());
cb_DriveThruType.Items.Add(reader["DriveThruType"].ToString());
cb_Patio.Items.Add(reader["Patio"].ToString());
cb_TrashEnclosure.Items.Add(reader["TrashEnclosure"].ToString());
cb_CounterStyle.Items.Add(reader["CounterStyle"].ToString());
cb_SelfServe.Items.Add(reader["SelfServe"].ToString());
cb_MenuboardType.Items.Add(reader["DigitalStatic"].ToString());
cb_RaisedCeiling.Items.Add(reader["RaisedCeiling"].ToString());
list_Notes.Items.Add(reader["Notes"].ToString());
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
Form View

Related

moving all the data from the list-box to the table in the database

I want to move all the data in the list-box to the table in the database I'm using C# and SQL in Visual Studio 2015 and I've tried to make it but not properly working and this is the code i use for inserting the data from the listbox. I need your help
private void Order()
{
using (SqlConnection connection = new SqlConnection(connectionString1))
{
String query = "INSERT INTO Tbl_order (OrderName,Quantity,Price,Serves_way,Date) VALUES (#OrderName,#Quantity, #Price,'"+servers+"','" + time1.ToString(format1)+"' )";
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#OrderName", lst_OrderName.Items.Add("#OrderName"));
command.Parameters.AddWithValue("#Quantity", lst_QTY.Items.Add("#Quantity"));
command.Parameters.AddWithValue("#Price", lst_Price2.Items.Add("#Price"));
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
}
the inserted data won't be the same objects in lst_OrderName or the number in lst_QTY and lst_Price2 . here the table in the database
enter image description here
how to insert all the data with there value to the database from the listbox ?
Looks like you want to use the ListBox.SelectedItem property. ListBox.Items.Add() adds a new item to your ListBox item collection and returns its index. So, what you are doing here is adding the string "#OrderName" to lst_OrderName, and say it already has 10 items, you are assigning the value 10 to the SQL parameter. Instead, you want to get the value like ...AddWithValue("#OrderName", lst_OrderName.SelectedItem), or if you only want the string value, use ...AddWithValue("#OrderName", lst_OrderName.GetItemText(lst_OrderName.SelectedItem).

Save listbox items in database after ordering

I have an asp.net page with two listboxes and a save button. The user needs to transfer items from listbox1 to listbox2 according to his order I mean that user can choose witch item come in the first place and which come next.
After that my system suggest the results (most commonly) that achieve the ordered items, I hope you understand
I did the transfer method between the two listboxes and it work good. But I'm stuck in the save method, it can save the items after being in listbox2 but not in the same order of transferring (user order).
Here is my code for save button:
protected void Button1_Click(object sender, EventArgs e)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
string str;
OracleCommand com;
OracleConnection con = new OracleConnection(strConnString);
try
{
con.Open();
for (int i = 0; i < ListBox2.Items.Count; i++)
{
str = "insert into Criteria values('" + ListBox2.Items[i].ToString() + "')";
com = new OracleCommand(str, con);
com.ExecuteNonQuery();
}
LabOut.Visible = true;
LabOut.Text = "Upload succesful!";
con.Close();
//Response.Write("Inserted");
}
catch (Exception)
{
LabOut.Visible = true;
LabOut.Text = "Upload failed!";
}
finally
{
con.Close();
con.Dispose();
}
}
The problem here is that database tables do not inherently have a concept of order. Retrieving rows from a table never guarantees an order unless you use a order by clause.
You should add an additional column to your table (named, for example, "Sequence" or "Order"). It can be an int or some other sortable value. You would then need to modify your insert statement:
str = "insert into Criteria(ItemValue, Sequence) values('" + ListBox2.Items[i].ToString() + "'," + i.ToString() + ")";
and retrieve the list using
str = "Select ItemValue from Criteria order by Sequence"
#fifo follow me
1st add a column in your database say it is SeqNo.
Then save your data with that. I mean generate SeqNo. for each listbox2 item and save it.
When you will fetch data from database into lintbox2 then use sql/linq ORDER BY on SeqNo. column and display them on which Order that you were saved. Simple.. :)

Inserting a row in database from DataGridview and Textfield

My problem is, I want to save data in the database from DataGridview and a Textbox. Here's my sample code:
connect.ConnectionString = coo;
connect.Open();
string str = string.Concat("insert into Sales values('", (1st column item in the datagridview), "','", textBox2.Text, "','", textBox3.Text, "','", textBox4.Text, "');");
command = new OleDbCommand(str, connect);
command.ExecuteNonQuery();
command.Connection = connect;
connect.Close();
Please provide guidance.
Inserting datGridView all rows to database:
We know to inserting values from textboxes and other data entry controls to database
but the values enter from dataGridView to database is little different than those ways
because here we have to insert all the rows which contains in dataGridView to database.
Click here for inserting values from textboxes to the datagridview control.So for the we
have to run a loop to to collect all the data from the all the rows from the database.
Event : The event to raise this code is saveButton_Click
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\naresh\My stuff\Thal tre tsks trim\Thalassemia\Data\thalsemia.accdb");
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
OleDbCommand cmd= new OleDbCommand("INSERT INTO table1(name,number,salory,) VALUES
('"+dataGridView1.Rows[i].Cells["Column1"].Value+"','"+dataGridView1.Rows[i].Cells["Column2"].Value+"',
'"+dataGridView1.Rows[i].Cells["Column3"].Value+" ' ",con);
cmd.ExecuteNonQuery();
}
con.Close();
I hope this code will help you.
to get the selected cell value you can use:
string Selection;
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
Selection=row.Cells[0].Value.ToString();
}
to add them in your query use parameters:
string query = "insert into Sales values(#param1,#param2,#param3,#param4)");
command = new OleDbCommand(query, connect);
command.Parameters.AddWithValue("#param1", Selection);
command.Parameters.AddWithValue("#param2", textBox2.Text);
command.Parameters.AddWithValue("#param3", textBox3.Text);
command.Parameters.AddWithValue("#param4", textBox4.Text);
command.ExecuteNonQuery();
command.Connection = connect;
connect.Close();
I will give you some guidelines how to do it but not provide your complete code:
You need a new column in your gridview and put a button/linkbutton in it as 'Edit/Save/Store' or whatever you want.
When user clicks that button, then ItemCommand Event of Gridview should be fired where you have to get the index of the selected row something like e.Rowindex (You can check the google for detailed tutorial on this) and once you have the index, that is the idea you need. In that event, you should save this data in the database.

How to Insert Data in Database through DataGridView in Windows Form Application

I am making a windows form application in c# , in which there is a grid view control which is bind to SQL server database. All want, to let user press CTRL + N and a new row appears as the first row of grid view and on entering data in that row, data should be inserted into database by pressing enter and with all validation checks. For this I am using text boxes, but don't know how to do it with grid view.
private void btnsave_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = DataConnection.GetConnection().CreateCommand();
cmd.CommandText = "insert into CustomerMaster(CustId,Name,City,State,Pin,ContactInfo) values(#custid,#name,#city,#state,#pin,#contactinfo)";
cmd.Parameters.Add(new SqlParameter("#custid", txtcustid.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtname.Text));
cmd.Parameters.Add(new SqlParameter("#city", txtcity.Text));
cmd.Parameters.Add(new SqlParameter("#state", txtstate.Text));
cmd.Parameters.Add(new SqlParameter("#pin", txtpin.Text));
cmd.Parameters.Add(new SqlParameter("#contactinfo", txtcontactinfo.Text));
bool ans = cmd.ExecuteNonQuery() > 0;
if (ans)
{
MessageBox.Show("Insertion Happens Successfully");
}
else
{
MessageBox.Show("Insertion doesnot Happens");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You have multiple questions. I will answer the "how to add empty row" one.
For that After you populate your dataset and before you bind it to the Grid you should add an empty row to the top of this dataset.
' insert a blank row at the top
Dim dr As DataRow = MyGrid.Tables(0).NewRow()
dr("MyFiled") = "0"
MyGrid.Tables(0).Rows.InsertAt(dr, 0)
There are many articles on internet showing how to save data. If you have problem with those please write your specific code here.

Populating a dropdown list from database

I have a asp.net page listing products (pulled from a database) with edit/delete buttons. The user can edit the product by clicking the edit button. I've been able to pull in data from the db to the textboxes based on the product selected. However, I am getting duplicate items in the dropdown box. It's only supposed to have 32 items and has 160 items (each item is appearing 5 times). I've used Items.Clear() but am still getting duplicates. Also the dropbox just shows the first item in the list rather than the appropriate item for that product that is currently in the db. Can anyone see what I may be doing wrong?
Thanks.
protected void Page_Load(object sender, EventArgs e)
{
this.Master.HighlightNavItem("Products");
string Mode = (Request.QueryString["Mode"]);
//Upon opening page, if this is an edit to existing product (populate product data)
if (Mode == "E")
{
if (!IsPostBack)
{
int ProductID = Int32.Parse(Request.QueryString["ID"]);
//Declare the connection object
SqlConnection Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
//Connect to the db
Conn.Open();
//Define the query
//string sql = "SELECT dbo.Vendor.VendorName, dbo.Vendor.VendorID, dbo.Product.ProductName, dbo.Product.ProductNumber, dbo.lu_Category.CategoryID, dbo.lu_Category.Description FROM dbo.Product INNER JOIN dbo.Vendor ON dbo.Product.VendorID = dbo.Vendor.VendorID INNER JOIN dbo.lu_Category ON dbo.Product.CategoryID = dbo.lu_Category.CategoryID WHERE ProductID=#ProductID";
string sql = "SELECT ProductName, ProductNumber, ProductDescription, Cost, Markup, Unit, QtyOnHand, ShippingWeight, dbo.Vendor.VendorID, VendorName, dbo.lu_Category.CategoryID, Description FROM Vendor, Product, lu_Category WHERE ProductID=#ProductID";
//Declare the Command
SqlCommand cmd = new SqlCommand(sql, Conn);
//Add the parameters needed for the SQL query
cmd.Parameters.AddWithValue("#ProductID", ProductID);
//Declare the DataReader
SqlDataReader dr = null;
//Fill the DataReader
dr = cmd.ExecuteReader();
//Loop through the DataReader
ddlVendor.Items.Clear();
while (dr.Read())
{
txtProductName.Text = dr["ProductName"].ToString();
txtProductNo.Text = dr["ProductNumber"].ToString();
txtDescription.Text = dr["ProductDescription"].ToString();
txtCost.Text = dr["Cost"].ToString();
txtMarkup.Text = dr["Markup"].ToString();
txtUnit.Text = dr["Unit"].ToString();
txtQty.Text = dr["QtyOnHand"].ToString();
txtWeight.Text = dr["ShippingWeight"].ToString();
ListItem li = new ListItem();
li.Text = dr["VendorName"].ToString();
li.Value = dr["VendorID"].ToString();
ddlVendor.Items.Add(li);
You should change your SQL query and remove the , type of joins.
Then test your query directly in your database to make sure you don't get doubles.
The rest of your code looks fine so i'm sure testing your query will solve your problem.
Do not use Comma Joins it's deprecated.
I think you should have used inner or outer join to get your data. With ',' separated joins you are receiving data from both tables. like 32 rows of one table are getting appneded with 5 rows of other table.

Categories

Resources