DataGridView Select command with parameters - c#

Basically what I want is the fill query of the data grid view like this
SELECT DealerName, OrderId, DealerId, OrderDate, ItemType, Price, Quantity, Total, TotalBill FROM dbo.DetailedRecord where DealerName=ComboboxName.SelectedValue
I can't see how to add parameters to it and I don't want to use the fill by toolstrip
Thanks

Why not use a stored procedure, then give it a dataset to fill it with your information?
Populate DataGridView from a Stored Procedure

Let's say you want to filter the data by some combobox.selectedvalue and you have a submit button, in that submit button code,you initialize a new datatable of the type yourdatasource.table like
YourDataSource.YourTableDataTable anything= new YourDataSource.YourTableDataTable();
yourdataadapter.fill(anything,parametervalue.tostring());
DataGridView1.datasource= anything;
And you're all set.

Try binding the table to your DataGridView.
See below for a simple example:
MySqlConnection conn = new MySqlConnection(connectionstring);
conn.Open();
string stmt = "SELECT DealerName, OrderId, DealerId, OrderDate, ItemType, Price, Quantity,
Total, TotalBill FROM dbo.DetailedRecord where DealerName=ComboboxName.SelectedValue";
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(stmt, conn);
da.Fill(ds, "dbo.DetailedRecord");
dataGridView1.DataSource = ds.Tables["dbo.DetailedRecord"];
conn.Close();

Simply pass your parameters as a string into your query. Use simple string concatenation (++). Watch how you create that search string carefully. Ensure that you initialize the DataTable first or else it will spring an error about null parameters: For example (Works on SQL Server , Mysql and Postgres)
String connectionString = "server = ...; db= ...; passwd = ....;";
DataTable dt_reservation_product_mix = new DataTable();
MySqlDataAdapter ad3;
ad3 = new MySqlDataAdapter("select `product`.`name`, `product`.`notes` from `product` where `product`.`code` = " + Convert.ToString(ComboboxName.SelectedValue) + "; ", connectionString);
ad3.Fill(dt_reservation_product_mix);
ad3.Dispose();

Related

how to use Gridview

I have a webform where I can display data from a mysql database on a page with a gridview. I have placed a Textbox on the webform, which I would like to search among database records.
string mysqlconnectionstring = "Server=server;Database=dataser;Uid=user;Pwd=passw;CharSet=utf8";
MySqlConnection MyConnection = new MySqlConnection(mysqlconnectionstring);
string query = "select * from Tools where NameofTool like '" + Search_txt.Text + "%'";
MySqlDataAdapter da = new MySqlDataAdapter(query, MyConnection);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1_0.DataSource = ds;
GridView1_0.DataBind();
So, if I understand the problem of extracting all the data from a datasource at the beginning, and then I want to give it the search. Of course I can interpret it wrong, sorry.
So the goal would be to get data from a DataSource, run it out with a GridView, then update the GridView according to the results.
Thanks :)
dt2.Rows.Clear();
cn.Open();
string comm = "SELECT * From Ansprechperson WHERE Name LIKE '%'+ #Firma + '%' AND KundenNr LIKE #KundenNr";
cmd = new SqlCeCommand(comm, cn);
cmd.Parameters.Add("#Firma", SqlDbType.NVarChar, 100).Value = editContactFilter.Text;
cmd.Parameters.Add("#KundenNr", SqlDbType.NVarChar, 100).Value = KundenNr;
using (adapt = new SqlCeDataAdapter(cmd))
{
adapt.Fill(dt2);
}
dataGridView2.DataSource = dt2;
cn.Close();
This is an example that worked for me. Please look into parameters to make your application SQL-Injection safe. Why Parameters protect you from SQL-Injection.
dt2 is a DataTable:
DataTable dt2 = new DataTable();
ideal approach would be search precise data from sql insdead first get all the data in data set and go for an other search.
kindly dont use inline queries like
string query = "select * from Tools where NameofTool like '" + Search_txt.Text + "%'";
instead use stored procedures. these inline queries are prone to sql injection.
so your ans would be "create a stored procedure with filter parameter"
and then bind GridView with returned data.

tinyint is shown as checkbox on gridview?

I have a several data column from my MySQL database, the type is tinyint(1)
my code in form
DataTable dt = new DataTable();
dt = PC.getValue(textBox.Text);
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeColumns();
and MyQuery
public DataTable getValue(string yearmonth)
{
connSIMRS.Open();
MySqlCommand command = new MySqlCommand();
string sql = "select * from table1 where yearmonth= '"+yearmonth+"'";
command.CommandText = sql;
command.Connection = connSIMRS;
//command.EndExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
//MessageBox.Show("");
connSIMRS.Close();
return dt;
}
can't post a picture but it turn into a checkbox. Could it be turn into a boolean? How can I show it as a string?
Yes, it is being turned into a boolean. Many ways to turn it into a string. Use a custom format, custom column, cast it from the database, etc.
Force MySql Connector to do it:
According to the MySQL Connector Docs , just add TreatTinyAsBoolean=false to your connection string.
However, I would just use a custom column in the GridView, as most cases I would want the booleans to be displayed as a checkbox, and this allows finer control over which ones I want displayed as text vs checkbox.
Add the obligitory string sql = "select * from table1 where yearmonth= '"+yearmonth+"'"; is bad. Don't do that EVER.

object reference not set to an instance of an object when using parameter

Can someone tell me how i can set the object reference to an instance? ....
Here, user_id is the parameter which takes a textbox value into the sql statement.
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
adap = new OracleDataAdapter("insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id,'172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt",con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20, "user_id").Value = textBox1.Text;
adap.Fill(ds,"A");
DataTable table = ds.Tables["A"];
dataGridView1.DataSource = ds.Tables["A"];
con.Dispose();
}
thanks!
edit
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
string str = "insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id, '172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt";
con.Open();
adap.InsertCommand = new OracleCommand(str, con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20).Value = textBox1.Text;
adap.InsertCommand.ExecuteNonQuery();
con.Dispose();
}
thanks everyone for your help!! i got it!
EDIT: There are multiple things wrong with your code:
You're not specifying the user_id parameter in the command, although it's in the SQL
You're trying to use the InsertCommand of the adapter even though you haven't specified any insertion SQL
You're trying to fill a dataset, but you haven't specified a query - just an insert command.
I suspect you shouldn't be using a data adapter at all. If you just need to insert some data, use:
using (var connection = new OracleConnection(...)
{
connection.Open();
string sql = "insert into banks_ben_branch_99 [... as before ...]";
using (var command = new OracleCommand(sql, conn))
{
command.Parameters.Add("user_id", OracleType.VarChar, 20)
.Value = textBox1.Text;
command.ExecuteNonQuery();
}
}
I suspect adap.InsertCommand is null in the following line:
adap.InsertCommand.Parameters.Add
On the previous line you use the following constructor:
adap = new OracleDataAdapter("insert into ...", con);
but this constructor initializes the SelectCommand, not the InsertCommand. Therefore adap.InsertCommand will still have its default value, null.
Your code then goes on to attempt to fill a DataTable using this adapter:
adap.Fill(ds,"A");
but this won't work either: you need a SelectCommand to do this.
To fill a DataSet, your code should probably look something like:
adap = new OracleDataAdapter("SELECT ... FROM ... WHERE ...", con);
adap.SelectCommand.Parameters.Add(... any parameters you need ...);
adap.Fill(ds, "A");
it is passing the break point now, no changes has been made to the oracle database tables! why is this happening.
I think you're misunderstanding how DataAdapters work.
To get data from the database into your DataTable, you need to:
Create an adapter with a SelectCommand
Call adapter.Fill to execute the SelectCommand and fill the DataTable with the result
To insert data into the database from your DataTable, you need to:
Insert a row into your DataTable with the data you want to insert
Create an adapter with an InsertCommand
Call adapter.Update to insert the data into the database.
Updating / Deleting rows in the database is similar to inserting, but uses UpdateCommand and DeleteCommand.
I think user_id is not a nullable column and it occurs when your parameter is empty. First thing is, parameter name does not match. After that, it still can happen when textbox is empty. It is better to check on client side for validation.
The parameter that you have given is null.

Select value from database based on dropdownlist value

I have database table leave_rec(name,date1,leave,ltype), a Dropdown list and a gridview.
I want to do such that,when I select month(e.g. february) in dropdown list the gridview should display all table values for february only(e.g.rohan leuva,2/28/2013,full,casual),means record which has month=2 (february).
How to overcome this issue? I tried but I can only display all the values in gridview at this moment. Any help would be greatly appriciated.
SqlConnection conn = new SqlConnection();
conn.ConnectionString=System.Configuration.ConfigurationManager.ConnectionStrings["leave"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("select date1,leave,ltype from leave_rec where name='" + DropDownList1.SelectedValue + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
The above code displays the date1,leave,ltype for dropdownlist1.selectedvalue. But now i want to have second dropdown in which months will be there. so when i select february in second one, grid should display value for dropdownlist1.selectedvalue for february only.
First, your query needs to be something like this:
select date1, leave, ltype from leave_rec where MONTH(date1) = 2 // February
Then, integrating it into your code:
SqlCommand cmd = new SqlCommand("select date1, leave, ltype from leave_rec where MONTH(date1) = #p1", conn);
cmd.Parameters.Add(new SqlParameter("p1", combo.SelectedKey));
Use parameters instead of string concatenation to avoid SQL Injection, see an example here: http://www.dotnetperls.com/sqlparameter
(Use your own control names for "combo.SelectedKey", of course)
I think problem in query , instead of name you have to write date1
SqlCommand cmd = new SqlCommand("select date1, leave, ltype from leave_rec where MONTH(date1) ='" + DropDownList1.SelectedValue + "'", conn);
Convert the dataset to DataTable
then - Filter it by dt.Filter=monthName.toString()
then bind it to GridView - dt.DefaultView;
Agree with #Saurabh, look into the use of Linq and Stored Procedures to force the use of types and modelling.

Datagrid view to fill based on columns

Below is my Datagridview code to get the data from employee table.
the problem am facing is ,my employee table have 10 columns (ID,emplNo,Dob,JoingData...etc)
i just want to fill my grid with only ID,EmplyNo and DOB.
but the below code get everything,please advise me what i suppose to do to get only particular column
string sql = "select * from Employee";
SqlConnection connection = new SqlConnection(CONNECTION_STRING);
//SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter = new SqlDataAdapter(sql, connection);
// DataSet ds = new DataSet();
ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, scrollVal, 5, "Employee");
connection.Close();
dgMessages.DataSource = ds;
dgMessages.DataMember = "tEmployee";
instead of
string sql = "select * from Employee";
do
string sql = "select ID, EmplyNo, DOB from Employee";
either change your select to only get the supset of what you want or use the designer:
it's a bit of a pain because you first have to add an unbound column and then edit the just added column to setthe DataPropertyName to a column-name in your resulting table - but it works.
You find this dialogs by clicking the "..." in the "columns" property of the PropertyEditor for the DataGridView or by clicking the little "Play"-Button on the top-right of the Grid in the designer (when it is selected)
Almost forgot: IMPORTANT: you need to add EVERY column and set Visible=False on those you don't want to see - I think this is different in WebForms where there is something like AutogenerateColumns.

Categories

Resources