how to use Gridview - c#

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.

Related

C# MySql Unknown column in where clause

After I try to output the password in the dataGrid, from the given Username in the txt_Username textbox, I get this error message:
MySql.Data.MySqlClient.MySqlException: "Unknown column 'Test' in 'where clause'"
MySqlDataAdapter da = new MySqlDataAdapter("Select Password from tbl_anmeldedaten Where Username=" + txt_Username.Text, con);
da.SelectCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
The exact cause of the error is that you are trying to execute the following query:
SELECT Password
FROM tbl_anmeldedaten
WHERE Username = Test;
Does it look like Test should have single quotes around it? Yes, it should, and you could add that to your raw query. But, concatenating a query like this in C# leaves open the possibility for SQL injection. A much better approach is to use prepared statements:
string sql = "SELECT Password FROM tbl_anmeldedaten WHERE Username = #val1";
MySqlCommand cmd = new MySqlCommand(sql, MySqlConn.conn);
cmd.Parameters.AddWithValue("#val1", txt_Username.Text);
cmd.Prepare();
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
// consume a record in the result set
}
You are using string concatenation which is a vector for SQL injection attacks. Perhaps the username in the text field is doing some SQL which it shouldn't be allowed to (for instance '' OR Test=1. There are plenty of resources on using parameterized queries which should remedy the problem.

Update/Insert MySQL values with C#

I am trying to both update and insert new database entries in my SQL database. The database runs through XAMPP because we wanted to test out if we could make it work using an external server.
I got the following code:
MySqlConnection sqlcon = new MySqlConnection("datasource=localhost;port=3306;username=root;password=");
MySqlDataAdapter mda = new MySqlDataAdapter("INSERT INTO projectDatabase.lesson (name, classRoom, TeacherID, active) VALUES ('"+ lessonName +"', '"+ className +"', '"+ UserData[0] +"', 1)", sqlcon);
MySqlDataAdapter mda2 = new MySqlDataAdapter("SELECT * FROM projectDatabase.lesson WHERE TeacherID = "+ UserData[0] +" AND active = 1", sqlcon);
sqlcon.Open();
DataSet ds = new DataSet();
mda2.Fill(ds, "lesson");
DataRow dr = ds.Tables["lesson"].Rows[0];
sqlcon.Close();
After this patch of code, the selected database items get inserted into arrays just fine, but there is no sign of an entry being added to the database.
The select works fine, but the insert (and update too for that matter) won't execute or even produce errors. I have been looking around for answers, but they all drastically change the way we have done the database queries so far. Is there a way to make it work using my current code?

DataGridView Select command with parameters

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();

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.

Invalid Column name when implementing search button

I'm working with C# and SQL Sever 2008, when I try to create a command for searching a record I got exception that said "Invalid Column name"
this is my code :
void cari()
{
koneksi.Open();
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = "+ textBox1.Text, koneksi);
SDA.Fill(dt);
koneksi.Close();
dataGridView1.DataSource = dt;
}`
the search command should be work as search engine, can anyone help me?
Well the immediate problem is that your WHERE clause will look something like:
where Subject = Foo
which is trying to compare the value of the Subject column with the value of the Foo column.
The hacky way of fixing this is to put quotes round the value. The better solution is to use parameterized SQL:
string sql = "SELECT * FROM jadwalkuliah where Subject = #Subject";
using (SqlConnection connection = new SqlConnection(...))
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connection))
{
connection.Open();
adapter.SelectCommand.Parameters.Add("#Subject", SqlDbType.VarChar)
.Value = textBox1.Text;
adapter.Fill(dt);
}
Additionally, note that you shouldn't be performing database accesses from a GUI thread. It's not clear whether this is a web app (in which case it's okay) or WPF/WinForms (in which case it's not).
Note that that will still try to make an exact match. For a "wildcard" match you'll need to change it to something like:
SELECT * FROM jadwalkuliah where Subject LIKE #Subject
... and add the parameter with something like "%" + textBox1.Text + "%". (You'll need to then think about escaping within that value, but that's another matter...)
You haven't quoted the value of subject:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = '"+ textBox1.Text + "'",
koneksi);
Or for a contains search:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM jadwalkuliah where Subject = '%"+ textBox1.Text + "%'", koneksi);
You shouldn't build queries this way. It is susceptible to SQL injection attacks.

Categories

Resources