I have two CheckedListBoxes, Standard Codes and Standard Details. Upon initialization, Standard Codes is populated from a query to the database.
InitializeComponent();
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Project;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter
("SELECT [StandardCode] FROM [dbo].[StandardCodesAndDetails]", conn);
adapter.Fill(ds);
this.lstBoxStandardCodes.DataSource = ds.Tables[0];
this.lstBoxStandardCodes.DisplayMember = "StandardCode";
conn.Close();
From this CheckedListBox, the user is able to select multiple Standard Code values. As these values are checked or unchecked, I want to run a query that will populate the Standard Details CheckedListBox with the related Standard Details from the database, with some Standard Codes having more than one Standard Detail. This is the part I'm not sure how to write. I'm not sure how to include checked CheckedListBox values in a SQL statement like this.
Any help at all would be appreciated. Thank you.
You have to create your sql statement dynamically instead of hard coding it.For example I will write a method which provide a sql statement based on user input like this.
public string CreateSQL(string userName,string password)
{
string sql="SELECT * FROM Table WHERE";
if(!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password))
{
sql+=" UserName='"+userName+"' AND Password='"+password+"'";
}
else if(!string.IsNullOrWhiteSpace(userName))
{
sql+=" UserName='"+userName+"'";
}
else if(!string.IsNullOrWhiteSpace(password))
{
sql+=" Password='"+password+"'";
}
else
{
sql=null;
}
return sql;
}
Related
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;
}
}
c# developers, can you say what wrong in that simple code?
public SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WpfApplication.Properties.Settings.BRDSConnectionString"].ToString());
public DataTable dt;
private void FillDataGrid()
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["WpfApplication.Properties.Settings.BRDSConnectionString"].ToString());
SqlCommand comm = new SqlCommand("select * from B_RDS_DIST",con);
SqlDataAdapter da = new SqlDataAdapter(comm);
dt = new DataTable();
da.Fill(dt);
CBDist.ItemsSource = dt.DefaultView;
CBDist.DisplayMemberPath = "NAM";
CBDist.SelectedValuePath = "KEY";
try
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (#NAM)", con);
cmd.Parameters.Add("#NAM", SqlDbType.VarChar, 255).Value="sadName";
da.InsertCommand = cmd;
da.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I can select, but can't insert. No exeptions here.
Table has only two columns KEY (PK,AI) and NAM (varchar 255).
May be I need to do something with connection to allow insert, or I missed something?
Thanks.
added
almost forgot, i use mdf file, so connectionString looks like:
"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BRDS.mdf;Integrated Security=True"
ANSWER - copy-paste pleas, i have no rputation.
Oh god, that was so dramatical old problem with generated Connection string!
Old connection string:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\BRDS.mdf;Integrated Security=True"
New connection string:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Im awsome\Documents\Visual Studio 2013\Projects\WpfApplication\WpfApplication\BRDS.mdf;Integrated Security=True"
Insert/Delete/Update works well.
I have only two "simple for you" questions now:
1) How can i use dataTable to update simple table in database. Do i need create data table with one column "NAM"?
2) Why is so hard to detect this damn simple problem with connection string!? :D
If this is how you want to do this....
Edited:
SqlDataAdapter lcDataAdapter = new SqlDataAdapter()
lcDataAdapter.InsertCommand = new SqlCommand("INSERT INTO B_RDS_DIST (NAM) VALUES (#NAM)", con);
lcDataAdapter.InsertCommand.Parameters.Add("#NAM", SqlDbType.VarChar, 255).Value="sadName";
lcDataAdapter.InsertCommand.ExecuteNonQuery();
Note: I would not use the InsertCommand method on the data adapter for inserting records, but this is a case of developer preference. The above should work for you though as-is.
That is not how you use DataAdapters, you need to call da.Update(dt) to invoke any Insert, Update, or Delete queries that need to be performed on the DataTable to reflect any changes you made to the original DataTable.
Either totally seperate out your insert command from the data adapter or add the row to the data table you populated from Fill(dt) and don't use separate connecting strings (it would actually be better to not write your own insert at all and use SqlCommandBuilder and just do da.InsertCommand = cmdBuilder.GetInsertCommand(); and it will automaticly build the insert based off of the Select you passed in to the DataAdapter)
I want to be able to execute a custom SQL query against a table adapter that I have. Is it possible to do this? Or can I only use the predefined queries on each table adapter in the dataset design view?
If I can't do this, how would I go about executing my SQL query against a table, and having the results display in my datagridview that's bound to a table adapter?
Thanks.
EDIT: I didn't explain myself properly. I know how to Add queries to a tableadapter using the dataset designer. My issue is i need to execute a custom peice of SQL (which i build dynamically) against an existing table adapter.
I posted a comment pointing to an example using VB which creates a class that extends TableAdapter. Instead of using the VB example and rewriting it in C# I will show how this can be done without creating a class that extends TableAdapter.
Basically create a BackgroundWorker to perform the sql query. You don't have to but it would be nice. Build the query string based on input from the user.
private void queryBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Initialize sqlconnection
SqlConnection myConnection;
//Convert date in to proper int format to match db
int fromDate = int.Parse(dateTimePickerStartDate.Value.ToString("yyyyMMdd"));
int toDate = int.Parse(dateTimePickerEndDate.Value.ToString("yyyyMMdd"));
//Setup Parameters
SqlParameter paramFromDate;
SqlParameter paramToDate;
SqlParameter paramItemNo;
SqlParameter paramCustomerNo;
//Fill the data using criteria, and throw any errors
try
{
myConnection = new SqlConnection(connectionString);
myConnection.Open();
using (myConnection)
{
using (SqlCommand myCommand = new SqlCommand())
{
//universal where clause stuff
string whereclause = "WHERE ";
//Add date portion
paramFromDate = new SqlParameter();
paramFromDate.ParameterName = "#FromDate";
paramFromDate.Value = fromDate;
paramToDate = new SqlParameter();
paramToDate.ParameterName = "#ToDate";
paramToDate.Value = toDate;
myCommand.Parameters.Add(paramFromDate);
myCommand.Parameters.Add(paramToDate);
whereclause += "(TableName.date BETWEEN #FromDate AND #ToDate)";
//Add item num portion
if (!string.IsNullOrEmpty(itemNo))
{
paramItemNo = new SqlParameter();
paramItemNo.ParameterName = "#ItemNo";
paramItemNo.Value = itemNo;
myCommand.Parameters.Add(paramItemNo);
whereclause += " AND (Tablename.item_no = #ItemNo)";
}
//Add customer number portion
if (!string.IsNullOrEmpty(customerNo))
{
paramCustomerNo = new SqlParameter();
paramCustomerNo.ParameterName = "#CustomerNo";
paramCustomerNo.Value = customerNo;
myCommand.Parameters.Add(paramCustomerNo);
whereclause = whereclause + " AND (Tablename.cus_no = #CustomerNo)";
}
string sqlquery = "SELECT * FROM TableName ";
sqlquery += whereclause;
//MessageBox.Show(sqlquery);
myCommand.CommandText = sqlquery;
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
this.exampleTableAdapter.ClearBeforeFill = true;
this.exampleTableAdapter.Adapter.SelectCommand = myCommand;
this.exampleTableAdapter.Adapter.Fill(this.ExampleDataSet.ExampleTable);
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I personally like the idea of coding a class that extends TableAdapter but this was a quick easy way of answering the OP's question. Sorry it took a year :)
Taken from here
To add a query to a TableAdapter in the Dataset Designer
Open a dataset in the Dataset Designer. For more information, see How to: Open a Dataset in the Dataset Designer.
Right-click the desired TableAdapter, and select Add Query.
-or-
Drag a Query from the DataSet tab of the Toolbox onto a table on the designer.
The TableAdapter Query Configuration Wizard opens.
Complete the wizard; the query is added to the TableAdapter.
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)
Could somebody take a quick peek at my ado.net code? I am trying to update the row from a dataset, but it just isn't working. I am missing some elemental piece of the code, and it is just eluding me. I have verified that the DataRow actually has the correct data in it, so the row itself is accurate.
Many thanks in advance.
try
{
//basic ado.net objects
SqlDataAdapter dbAdapter = null;
DataSet returnDS2 = new DataSet();
//a new sql connection
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Server=myserver.mydomain.com;"
+ "Database=mydatabase;"
+ "User ID=myuserid;"
+ "Password=mypassword;"
+ "Trusted_Connection=True;";
//the sqlQuery
string sqlQuery = "select * from AVLUpdateMessages WHERE ID = 21";
//another ado.net object for the command
SqlCommand cmd = new SqlCommand();
cmd.Connection = myConn;
cmd.CommandText = sqlQuery;
//open the connection, execute the SQL statement and then close the connection.
myConn.Open();
//instantiate and fill the sqldataadapter
dbAdapter = new SqlDataAdapter(cmd);
dbAdapter.Fill(returnDS2, #"AVLUpdateMessages");
//loop through all of the rows; I have verified that the rows are correct and returns the correct data from the db
for (int i = 0; i <= returnDS2.Tables[0].Rows.Count - 1; i++)
{
DataRow row = returnDS2.Tables[0].Rows[i];
row.BeginEdit();
row["UpdatedText"] = #"This is a test...";
row.EndEdit();
}
//let's accept the changes
dbAdapter.Update(returnDS2, "AVLUpdateMessages");
returnDS2.AcceptChanges();
myConn.Close();
}
I think you need an update query in your data adapter. I know, this sucks... Alternatively you can use CommandBuilder class to automatically generate queries for CRUD operations.
example at: http://www.programmersheaven.com/2/FAQ-ADONET-CommandBuilder-Prepare-Dataset
You might be able to use SqlCommandBuilder to help out. After the Fill call, add the following statement. That will associate a command builder with the data adapter and (if there is a primary key available) it should generate the update statement for you. Note that there is some expense behind the command builder. It may not be much relative to everything else, but it does involve looking at schema information (to get primary key information, field names, field types, etc.) for the table and generating INSERT, DELETE, and UPDATE statements involving all fields in the table.
SqlCommandBuilder cb = new SqlCommandBuilder(dbAdapter);
Wait, why not something like
update AVLUpdateMessages set UpdatedText = 'This is a test...' where id = 21
If you're picking through all the rows of a table to update one at a time, you're probably doing it wrong. SQL is your friend.