Search in datagrid using combo box - c#

i have to search data from the text box in datagrid using c#
My code is
private void button_Search_Click(object sender, EventArgs e)
{
sqlcon.Open();
//DataSet ds15 = new DataSet();
DataTable dt= new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
Getting error Arguement exception was unhandled
I want to search through combo box

there is no constructor match your parameters on SqlDataAdapter
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from TableName where Field like '%{0}%'",
comboBox_Search.Text), sqlcon);

Query every time to the database is not a preferable approach. Instead take a BindingSource object and fill the source once. Then use BindingSource.Filter property to get relevant result set and bind the result set to grid.
Have a look at this and and this link.
Also, to fix your issue you can try like this:
....
sqlcon.Open();
string query = string.Format("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
SqlCommand cm = new SqlCommand(query, sqlcon);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
....

How does the SqlDataAdapter know where to get the result from?
You are not initializing the constructor for your SqlDataAdapter properly. The first argument is the full select statement and the second argument is your connection string.
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from atm_status where Table like '%{0}%'", comboBox_Search.Text), sqlcon);

private void txt_Searchque_TextChanged(object sender, EventArgs e)
{
string connector_string = "datasource = localhost;port=3306;username=root;password=;";
MySqlConnection sqlcon = new MySqlConnection(connector_string);
sqlcon.Open();
string query = string.Format("Select * from oep.quiz where que like '%{0}%'", txt_Searchque.Text);
MySqlCommand cmd = new MySqlCommand(query, sqlcon);
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adpt.Fill(dt);
dataGridView1.DataSource = dt;
}

Related

Save edits from DataGridView to Datatable

Hi i want to save edits in DataGriView to datatable , i tried that code but an error shows 'System.ArgumentOutOfRangeException: 'The index was out of range. It must not be negative and must be smaller than the size of the collection.
Parameter name: index '' help
private void button11_Click(object sender, EventArgs e)
{
con.Open();
String query = "SELECT * FROM Taom";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
dataGridView1.DataSource = dt1;
SDA.Fill(dt);
dataGridView1.Rows[2].Cells[2].Value = Math.Atan((Convert.ToDouble(dataGridView1.Rows[5].Cells[2].Value)) / (Convert.ToDouble(dataGridView1.Rows[6].Cells[2].Value)));
dataGridView1.Rows[3].Cells[2].Value = Math.Atan((Convert.ToDouble(dataGridView1.Rows[7].Cells[2].Value)) / (Convert.ToDouble(dataGridView1.Rows[8].Cells[2].Value)));
ds1.Tables.Add(dt);
con.Close();}
I changed my code to that code no errors showed after i run values on datagridview change but no changes in datatable !!!
string query = "SELECT * FROM [dbo].[Taom]";
SqlConnection conn = new SqlConnection(#"Data Source=STE-P0024818PW;Initial Catalog=test;Integrated Security=True");
conn.Open();
SqlDataAdapter SDA = new SqlDataAdapter(query, conn);
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
SDA.Fill(dt);
dt.Rows[0]["Contents"] = "98"; //Before it was 10
dt.Rows[1]["Contents"] = "99"; //Before it was 11
ds1.Tables.Add(dt);
conn.Close();
Fill the right value inside your table and after pass the table rightly filled in your datasource, don't change this directly in the gridview like:
I try myself and it works:
private void Run()
{
string query = "SELECT * FROM dbo.[Anrufthema]";
SqlConnection conn = new SqlConnection("MyConnectionString");
conn.Open();
SqlDataAdapter SDA = new SqlDataAdapter(query, conn);
DataSet ds1 = new DataSet();
DataTable dt = new DataTable();
SDA.Fill(dt);
dt.Rows[0]["Anrufthema"] = "98"; //Before it was 10
dt.Rows[1]["Anrufthema"] = "99"; //Before it was 11
ds1.Tables.Add(dt);
conn.Close();
}
My Result, it works !

Updating Data GridView using the selected value inside the dropdown list

I have a dropdownlist and a gridview.. Dropdown list contains the list of the tables I have in my database. What I want is, when I select a particular table name from the dropdownlist, I want all the columns and data inside that particular table display inside the gridview.
This is my code...
Code for displaying the list of tables inside the dropdown is success.. But to bind the columns and data inside the gridview is not success..
Please Help me...
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "table_name";
DropDownList1.DataValueField = "table_name";
DropDownList1.DataBind();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//+DropDownList1.selecteditem.text +
GridView1.DataBind();
con.Close();
}
}
This is a bad idea on several levels. First you are wide open to SQL injection. Second, you are giving everyone full view access to every column and row of every table.
But the reason you are not getting data is because the select string does not make sense. It should look like this
"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"
But this is how a proper sql connection should look like.
//create a new datatable
DataTable dt = new DataTable();
//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = #TableName";
//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
//replace the token with the correct value
command.Parameters.Add("#TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
//open the connection
connection.Open();
//load the data of the select into the datatable
dt.Load(command.ExecuteReader());
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//but you can also skip the datatable and bind directly to the gridview
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}

Getting empty result in output when using Select statement in Grid-View

Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code
using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
con1.Open();
SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con1.Close();
}
Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here
You have used the DataSet not DataTable. So you could either do this:
da.Fill(ds,"tbl");
GridView1.DataSource = ds.Tables[0];
Or use a DataTable instead:
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
Also you should always use parameterized queries to avoid SQL Injection. Something like this:
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=#userId", con1);
cmd.Parameters.AddWithValue("#userId", (String)Session["uid"]);
Also have a look at this: Can we stop using AddWithValue() already?
you need to set DataTable instead of DataSet
GridView1.DataSource = ds.Tables["Pm"];
#PIYUSH Itspk please check query and replace
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=" +Session["uid"].tostring()+ ", con1);
i think its help you if any other query please notify me

c# Select sql database data using datetimepicker set with date range

I am trying to make c# program, where I have to make a database report to be previewed at the datagridview. Data will be selected using the datetimepicker. I have written the code, it works but then if the date selected is of different months. No records appear
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
please help me check my code and tell me what might be wrong or missing.
Use profiler to check the query that hits the DB. I suspect it's a date formatting issue.
Maybe this question can help you with logging the queries that hit the database:
Hope this helps:
Select * from [Table] where StartDate between '06/13/2016' and '10/13/2016'
The above query fetches records between months 06 and 10. Make sure that string in the data variable is in the above format. Also the column type in the database is date.
Check and remove special characters, if any.
Mark this as answer if you find this useful.
Try this for your select query. I have changed one of your select variable because it ambiguous for the Date datatype.
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
//string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
//Changed query for getting data from DB according to the date
string data = "SELECT CreatedDate, Process, Actual, Target FROM database WHERE DATE_FORMAT(CreatedDate,'%Y-%m-%d') BETWEEN '"+this.fromDatePicker.Value.ToString("yyyy-MM-dd")+"' AND '"+this.toDatePicker.Value.ToString("yyyy-MM-dd")+"' order by CreatedDate desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}

Using Select query to display data in a data grid view

I am trying to display a table data of my db in a DataGridView.here is my code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" +
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
//adp.Fill(dt);
DataGridView.DataSource = adp.Fill(dt);
}
The code is not giving any error now but but it dosent display the data from my table in my grid ?
You are using class name instead of object (instance) name of DataGridView, check in the html what is ID/name of DataGridView, It is probably Win Forms and you do not have DataBind method there. DataBind method is defined for GridView for ASP.net. Find more about DataGridView here.
DataGridViewObject.DataSource = adp.Fill(dt);
this is the answer to my quetion , hope it helps others who are new to this
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
//objcmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adp.Fill(dt);
//MessageBox.Show(dt.ToString());
dataGridView1.DataSource = dt;
Create an instance of DatagridView:
DataGridView dview = new DataGridView();
....
dview.DataSource = adp.Fill(dt);
dview.DataBind();
You are directly accessing DataGridView properties and tryingto add data to the class. You need to create and an instance of a DataGridView first. Then assign the datable to the object.
Than bind the data to the DataGridView, otherwise the data is not bound to the control and will not be displayed.
DataGridView view = new DataGridView();
dview.DataSource = adp.Fill(dt);
dview.DataBind();
You are not exectuting the query
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
DataTable dt = new DataTable(); using
(SqlDataReader sqlDataReader = objcmd.ExecuteReader())
{
dt.Load(sqlDataReader);
sqlDataReader.Close();
}
DataGridView dataGridView1 = new DataGridView();
dataGridView1.DataSource = dt;

Categories