C# Fill combo box from SQL DataTable - c#

DataTable _dt = new DataTable();
using (SqlConnection _cs = new SqlConnection("Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True"))
{
string _query = "SELECT * FROM Doctor";
SqlCommand _cmd = new SqlCommand(_query, _cs);
using (SqlDataAdapter _da = new SqlDataAdapter(_cmd))
{
_da.Fill(_dt);
}
}
cbDoctor.DataSource = _dt;
foreach(DataRow _dr in _dt.Rows)
{
cbDoctor.Items.Add(_dr["name"].ToString());
}
There was an Error...
The result is System.Data.DataRowView instead of data from database..

I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable, you can do it this way:
using (SqlConnection sqlConnection = new SqlConnection("connstring"))
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
cbDoctor.Items.Add(sqlReader["name"].ToString());
}
sqlReader.Close();
}
For more information take a look at SqlDataReader reference on MSDN.
In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.

You could also specify DisplayMember property of combobox to any of the column name.
For example if you want to display Name field, you could do
Combobox1.DisplayMember="Name";

I think the problem is that you are trying to insert multiple columns into a comboBox (which can accept only one column). Adjust your SELECT statement so that it combines all of the data you need into one column:
Example:
SELECT Name + ' ' LastName + ' '+ ID AS 'DoctorData' FROM Doctor
By using the + operator you can combine multiple columns from the database, and represent it as a single piece of data. I think that your code should work after that (you can even comment the foreach loop, I think that adding data source to your comboBox will be enough)

Related

Getting data in textbox

I want to do " When I write "Item Code" on textbox and click search, It will search & found that item in sql database which has that item code . And Bring it name to textbox2(ITEM NAME). How can I do it ? I can bring it on colomn/raw but Idk how can I bring that item name on textbox2
I can search data on database and bring it to dataGridview . With this code
if (textBox1.Text.Trim() == "") errorProvider1.SetError(textBox1, "Fiil in the blanks");
else errorProvider1.SetError(textBox1, "");
conn.Open();
string regs = "SELECT * from stackTable where itemCodu=#Cod";
SqlCommand cmd = new SqlCommand(regs, conn);
cmd.Parameters.AddWithValue("#cod", textBox1.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridView.DataSource = dt;
conn.Close();
---operation sequence ( Which I want to do :D )
Search on Database
If found, bring data on Textbox2
If didn't find, Error provider, message textbox
So you have a datatable, all you should have to do is to check the count after the fill with a simple if statement:
if(dt.rows.count == 0)
{
MessageBox.Show("Not Found!!");
}
else
{
textBox2.DataBindings.Add("Text", dt, "the column you want to use for textbox2");
}
You should also be using using statements so that all the objects are disposed of properly.
here's an example of how I would write what you have:
textbox2.DataBinding.Clear(); //clear the databinding so it can be added for the new data found.
using(SqlConnection conn = new SqlConnection("Your connection string here")
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * from stackTable where itemCodu=#Cod")
{
da.SelectCommand.Parameters.Add("#Cod", sqlDbType.VarChar).Value = textBox1.Text; //see comment below for this change
da.fill(dt);
if (dt.Rows.Count == 0)
{
//display not found message
}
else
{
//bind to textbox (described above)
}
}
Also note, instead of allowing the parameter to be implicitly typed, it is often better to specify the type of data the parameter should receive. This can be done by using Add instead of AddWithValue
cmd.Parameters.Add("#cod", SqlType.VarChar).Value = textBox1.Text;
The last thing to note with your code is that you can use the sqlDataAdapter without the SqlCommand.
One other thing I thought I should add:
If you know you will only ever receive 1 or 0 rows from the search, and you're not interested in binding the data, you could simply just set the textbox's .Text to the column of the row in the datatable.
For example, if you wanted to display a column in your table named Item you could simply use
textBox2.Text = dt.Rows[0]["Item"].ToString();

C# sqlite copy a datatable to another datatable in faster way

Can anyone share how to coding copy a datatable to another datatable in faster way for C# sqlite? Thanks.
And also need to change column name also. i tried to manually select and update, but encountered error. Appreciate for your sharing. Thanks.
or how can i amend the column header when display datatable in datagridview? Thanks.
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd4 = new SQLiteCommand();
cmd4 = dbConnect.CreateCommand();
cmd4.CommandText = "DELETE FROM GroupEven";
cmd4.ExecuteNonQuery();
cmd4.CommandText = "SELECT Day, Day_ID, Standard, Timeslot1_TeacherName, Timeslot1_Subject, Timeslot2_TeacherName, Timeslot2_Subject, Timeslot3_TeacherName, Timeslot3_Subject, Timeslot4_TeacherName, Timeslot4_Subject, Timeslot5_TeacherName, Timeslot5_Subject, Timeslot6, Timeslot7_TeacherName, Timeslot7_Subject, Timeslot8_TeacherName, Timeslot8_Subject, Timeslot9_TeacherName, Timeslot9_Subject, Timeslot10_TeacherName, Timeslot10_Subject, Timeslot11_TeacherName, Timeslot11_Subject FROM TimetableFinal";
DataTable dt4 = new DataTable();
SQLiteDataAdapter da4 = new SQLiteDataAdapter(cmd4);
da4.Fill(dt4);
foreach (DataRow dr4 in dt4.Rows)
{
cmd4.CommandText = "INSERT INTO TimetableFinal2 (Day, Day_ID, Standard, 7:30am-8:00am, 7.30am-8.00am, 8:00am-8:30am, 8.00am-8.30am, 8:30am-9:00am, 8.30am-9.00am, 9:00am-9:30am, 9.00am-9.30am, 9:30am-10:00am, 9.30am-10.00am, 10:00am-10:20am, 10:20am-10:50am, 10.20am-10.50am, 10:50am-11:20am, 10.50am-11.20am, 11:20am-11:50am, 11.20am-11.50am, 11:50am-12:20pm, 11.50am-12.20pm, 12:20pm-12:50pm, 12.20pm-12.50pm) VALUES (#Day, #Day_ID, #Standard, #7:30am-8:00am, #7.30am-8.00am, #8:00am-8:30am, #8.00am-8.30am, #8:30am-9:00am, #8.30am-9.00am, #9:00am-9:30am, #9.00am-9.30am, #9:30am-10:00am, #9.30am-10.00am, #10:00am-10:20am, #10:20am-10:50am, #10.20am-10.50am, #10:50am-11:20am, #10.50am-11.20am, #11:20am-11:50am, #11.20am-11.50am, #11:50am-12:20pm, #11.50am-12.20pm, #12:20pm-12:50pm, #12.20pm-12.50pm)";
cmd4.Parameters.AddWithValue("#Day", dr4["Day"].ToString());
SQLite does support Joinings Insert statements, something like this.
INSERT INTO 'tablename' ('column1', 'column2')
VALUES
('data1', 'data2'),
('data3', 'data4'),
('data5', 'data6'),
('data7', 'data8');
See this.. http://www.sqlite.org/lang_insert.html
and then execute this in one go. Also, Make sure you do this in transactions and wrap around in using statements
using(var dbConnect = new SQLiteConnection("DataSource=school.db;Version=3;"))
{
dbConnect.Open();
using(var transaction = dbConnect.BeginTransaction())
{
string insertQuery = ...// your insert query
using (var cmd = dbConnect.CreateCommand())
{
cmd.CommandText = insertQuery;
foreach (DataRow dr4 in dt4.Rows)
{
cmd.Parameters.AddWithValue(...);
}
cmd.ExecuteNonQuery()
}
transaction.Commit();
}
}
Regarding your second part: How can i amend the column header when display datatable in datagridview,
thats totally separate, has nothing to do with Sqlite insertions.
After getting the data source you can do something like this
dataGridView1.Columns[i].HeaderText = "My New header";

populate combobox with values from another form

I might ask a stupid question, but I can't find it on the internet.
I have a combobox and I would like to retrieve some data from another form where the info is typed and saved by the user. If anyone is willing to help, I'll be greatful. Thanks
I used this code
string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=BusManager; Trusted_Connection=True;";
string select = "SELECT * FROM TipAutocar";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(select, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cmbTip.Items.Add(dr["Model", "Type"]);
}
con.Close();
And it worked..but is this possible to get for eg "Model" + "Type"?
And I get this error ->
Error 1 No overload for method 'this' takes 2 arguments
If I understood your question correctly, you want to add different column values to your ComboBox concatenated. So, it's as simple as that:
while (dr.Read())
{
cmbTip.Items.Add(dr["Model"].ToString() + " " + dr["Type"].ToString());
}

Error with databound DataGridView Display Textbox's Text

I have a datagridview (dgvSelectedItem)and I want it to display some values from textboxes but I have this error
Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound
My code is:
DataTable dt = new DataTable();
string conn = "server=.;uid=sa;pwd=123;database=PharmacyDB;";
Okbtn()
{
SqlDataAdapter da = new SqlDataAdapter("select UnitPrice from ProductDetails where prdctName like '"+txtSelectedName.Text + "'", conn);
da.Fill(dt);
dgvSelectedItem.DataSource = dt;
//this code work but when I add these lines the Error appear
dgvSelectedItem.Rows.Add(txtSelectedName.Text);
dgvSelectedItem.Rows.Add(txtSelectedQnty.Text); }
Thanks in advance
UPDATED Per OP Comment
So you want a user to enter the product name and quantity, then to run a query against the database to retrieve the unit price information. Then you want to display all of that information to your user in a DataGridView control.
Here is what I suggest:
Include the prdctName field in your SELECT clause.
If you want to bind all relevant data to a DataGridView including the Quantity variable and your TotalPrice calculation, then include them in your SELECT statement. When you bind data to the control from an SQL query like this, the result set is mapped to the grid. In other words, if you want information to be displayed when setting the DataSource property then you need to include the information in your SQL result set.
Don't use LIKE to compare for prdctName as it slightly obscures the purpose of your query and instead just use the = operator.
In addition from a table design perspective, I would add a UNIQUE INDEX on the prdctName column if it is indeed unique in your table - which I sense it likely is. This will improve performance of queries like the one you are using.
Here is what your SQL should look like now:
SELECT prdctName, UnitPrice, #Quantity AS Quantity,
UnitPrice * #Quantity AS Total_Price
FROM ProductDetails
WHERE prdctName = #prdctName
A few other suggestions would be to use prepared SQL statements and .NET's using statement as already noted by Soner Gönül. I'll try to give you motivation for applying these techniques.
Why should I use prepared SQL statements?
You gain security against SQL Injection attacks and a performance boost as prepared statements (aka parameterized queries) are compiled and optimized once.
Why should I use the using statement in .NET?
It ensures that the Dispose() method is called on the object in question. This will release the unmanaged resources consumed by the object.
I wrote a little test method exemplifying all of this:
private void BindData(string productName, int quantity)
{
var dataTable = new DataTable();
string sql = "SELECT prdctName, UnitPrice, #Quantity AS Quantity, " +
"UnitPrice * #Quantity AS Total_Price " +
"FROM ProductDetails " +
"WHERE prdctName = #prdctName";
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#prdctName", productName);
cmd.Parameters.AddWithValue("#Quantity", quantity);
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
}
}
}
Here's a sample input and output of this method:
BindData("Lemon Bars", 3);
I searched over the internet and looks like there is no way to add new rows programmatically when you set your DataSource property of your DataGridView.
Most common way is to add your DataTable these values and then bind it to DataSource property like:
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["UnitPrice"] = txtSelectedName.Text;
dt.Rows.Add(dr);
dt.Rows.Add(dr);
dgvSelectedItem.DataSource = dt;
Also conn is your connection string, not an SqlConnection. Passing SqlConnection as a second parameter in your SqlDataAdapter is a better approach in my opinion.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Finally, don't forget to use using statement to dispose your SqlConnection and SqlDataAdapter.
I assume you want to use your text as %txtSelectedName.Text%, this is my example;
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=123;database=PharmacyDB;"))
using(SqlCommand cmd = new SqlCommand("select UnitPrice from ProductDetails where prdctName like #param"))
{
cmd.Connection = conn;
cmd.Parameter.AddWithValue("#param", "%" + txtSelectedName.Text + "%");
using(SqlDataAdapter da = new SqlDataAdapter(cmd, conn))
{
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["UnitPrice"] = txtSelectedName.Text;
dt.Rows.Add(dr);
dt.Rows.Add(dr);
dgvSelectedItem.DataSource = dt;
}
}

Displaying selected data in a datagridview

I have codes here that display all data in access database. Is it possible to only display specific or selected data from my database?
here is my code :
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\SISC-STRONGHOLD\MIS!\wilbert.beltran\SEEDBucksDbase.accdb";
string query = "SELECT * From TableAcct";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns["UserPassword"].Visible = false;
}
conn.Close();
}
thanks! :)
To query for a last name (assuming the column in the table is called LastName), try this:
string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";
Of course, you have to be careful of SQL Injection attacks. I'm not familiar with using paramaterized queries in Access.
Is this a public form, or internal just for you (or trusted users)?
you just need to write down where condition in you query will do work for you,
Following is example of it
string query = "SELECT col1,col2 From TableAcct where col1=value";
This will fetch data that satisfy you condition and bind with the grid control.
And instead of * in select list give name of the columns you want to display.
for getting value form control like textbox
string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";
Note- make use of sqlparameter to avoid SQLInjection , above is just an example.
string query = "SELECT (SelectedColumnNames) From TableAcct Where LastName=(LastName)";
INstead of Searching with a * in a Query enter the desired columns for ex:-
string query = "SELECT phno,address,FirstName From TableAcct where LastName ='"+txt1.text +"'";

Categories