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();
Related
Need some help with DatagridView & DataTable.
Basically I have a DatagridView which OnLoad populates with the data from a table in SQL Server
When I click a button on UI, this DataGridView adds a new column to the front of grid "Update" which is a checkbox column
Now when the user ticks all those rows which needs updating and clicks Update...
I want to update all the rows which are ticked (for example: I wish to set the owner of these rows from Person A to Person B)
I've looked at DataTable but I'm confused
My logic is to add all the selected columns to a DataTable and send this to a stored procedure in SQL Server which would update the values.
If I'm not mistaken, I shall be sending a DataTable with just an ID column followed by From & To (owners) to the stored procedure.
Please guide me if I'm wrong, any help would be immensely appreciated.
private DataTable getDataGridID()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
foreach (DataGridViewRow row in dgTeamDashboard.Rows)
{
if (Convert.ToBoolean(row.Cells["Update"].Value) == true)
dt.Rows.Add(row.Cells["ID"].Value);
}
return dt;
}
I've now progressed upto this point where I have a DataTable with all those ID's whose update column is ticked.
I'm hopeful, I'm heading in the right direction. Comment if I'm not
Further Update:
I've now create a stored procedure which accepts UserDefinedTableType and a destinationOwnerID as parameter and updates the actual table with the supplied OwnerID for all those leads whose ID matches the records from DataTable.
Create Procedure [activity].[udpUpdateActivityLead]
#ActivityLeadTable ActivityLeadType READONLY,
#OwnerTo int
AS
BEGIN
UPDATE [activity].[tblActivity]
set [activity].[tblActivity].[IDOwner]= #OwnerTo
from #ActivityLeadTable
where [activity].[tblActivity].[ID]=[#ActivityLeadTable].[ID];
END
Finally I got this function in my UI which works like a GEM. Happy ending...I can go to sleep now...
public void updateActivityLead()
{
SqlConnection con = new SqlConnection(OpSupLib.MyConnectionString);
SqlCommand cmd = new SqlCommand();
if (con.State == System.Data.ConnectionState.Closed)
con.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "[activity].[udpUpdateActivityLead]";
SqlParameter p1 = new SqlParameter();
p1.ParameterName = "#ActivityLeadTable";
p1.Value = getDataGridID();
cmd.Parameters.Add(p1);
SqlParameter p2 = new SqlParameter();
p2.ParameterName = "#OwnerTo";
p2.Value = ((ComboBoxItem)cmbUpdateTo.SelectedItem).HiddenValue;
cmd.Parameters.Add(p2);
cmd.Connection = con;
cmd.ExecuteNonQuery();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}
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;
}
}
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)
This is basically a search tool. When I type some thing in a combobox, the combobox drops down and will show me suggestions (something like Google search bar)
I created a procedure which does some complex calculations, which take one parameter and returns some rows. Then I created a combobox event (On Update Text).
And in the event handler I wrote this code:
private void combobox_TextUpdate(object sender, EventArgs e)
{
this.combobox.Items.Clear();
DataTable List = new DataTable();
if (this.combobox.Text.Length > 0)
{
List = searchIt(combobox.text);
foreach (DataRow Row in List.Rows)
{
this.combobox.Items.Add(Row.ItemArray.GetValue(0).ToString());
}
this.combobox.DroppedDown = true;
}
}
static public DataTable searchIt(string STR)
{
string connectionString = McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;
SqlConnection con = new SqlConnection(connectionString);
DataTable DT = new DataTable();
con.Open();
SqlDataAdapter DA = new SqlDataAdapter("USE [McFarlane Industries] " +
"EXEC search " +
STR, connectionString);
DA.Fill(DT);
con.Close();
return DT;
}
The function searchIt executes the stored procedure and it returns a DataTable. The stored procedure is working fine in SQL Server Management Studio.
But in the application it is not working correctly in some cases.
When I type [space], then it throws an exception and it says stored procedure needs parameter which is not provided.
There are many other characters when I type them it throws exception that invalid character at end of string "my string".
Any suggestion how could I achieve my goal.
Call your stored procedure with sqlcommand to fill your datatable
using (SqlConnection scn = new SqlConnection(connect)
{
SqlCommand spcmd = new SqlCommand("search", scn);
spcmd.Parameters.Add("#blah", SqlDbType.VarChar, -1); //or SqlDbType.NVarChar
spcmd.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter(spcmd))
{
da.Fill(dt);
}
}
static public DataTable searchIt(string STR)
{
string connectionString = McFarlaneIndustriesPOSnamespace.Properties.Settings.Default.McFarlane_IndustriesConnectionString;
SqlConnection con = new SqlConnection(connectionString);
DataTable DT = new DataTable();
con.Open();
SqlCommand command = new SqlCommand("Name_of_Your_Stored_Procedure",con);
command.CommandType=CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#parameter_name",SqlDbType.NVarChar));
command.Parameters[0].Value="Your Value in this case STR";
SqlDataAdapter DA = new SqlDataAdapter(command);
DA.Fill(DT);
con.Close();
return DT;
}
Important :
'parameter_Name' and 'Name_of_Your_Stored_Procedure' should be replaced by yours which you have in database. And value of parameter could be like "abc" (combox.Text)
Command and its type, its text are necessary.
Adding parameters depends upon your stored procedure. They can be 0,1 or more but once they are added their values must be given. conn(connection) can be passed to new SqlCmmand() or new SqlDataAdapter()
No need of things like 'use' and 'exec'
Following me and this link might be helpful in future for stored procedures
http://www.codeproject.com/Articles/15403/Calling-Stored-procedures-in-ADO-NET
Two optional Suggestions for you
use variable name 'list' instead of 'List' (you used) however you will not get problem with this name until you add a namespace using System.Collections.Generic; but you may need to use this namespace in future.
Use only list.Rows[0].ToString(); no need to get itemarray then get value when you are working with data in strings;
In the application im writing im connecting to a SQL database, then using an Adapter to hold the returned results but now I want to filter the results with .RowFilter three times return the filtered result each time to Textbox. I'm not sure if this is best executed with an if statement or with some Switch statement. Heres the code for a better idea of what im trying to do.
using (con)
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDnumber);
//SQLConnection Established and Opened
SqlDataAdapter adapter = new SqlDataAdapter(selectSQL, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
//Adapter Created and Filled
DataView dvQ = dt.DefaultView;
dvQ.RowFilter = "AccountType = Q";
QualVol.Text = "TotalVolume".ToString();
//First Filter then Change QualVol textbox text to Column data TotalVolume
dvQ.RowFilter = "AccountType = N";
NonVol.Text = "TotalVolume".ToString();
//Filter original DataView then Change NonVol textbox text to Column data TotalVolume
dvQ.RowFilter = "AccountType = M";
MidVol.Text = "TotalVolume".ToString();
//Filter original DataView then Change NonVol textbox text to Column data TotalVolume
}
As per dotnetperls performance of a switch is better than an if but also gives a good clue on what situation an if performs better than the switch
http://www.dotnetperls.com/if-switch-performance