Select value from database based on dropdownlist value - c#

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.

Related

How can i create a customizable SQL function in Visual Studio

Is it possible to create an extendable SQL query in Visual studio?
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select geneID from Table3 where geneID in(" + filterdata + ")";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Can this be extended to select any possible parameter from any possible tables using any possible conditions. I think it would look something like the following:
Select [Variable 1,Variable 2...] from [Table 1, Table2...] where [Condition1, Condition 2...]
The variables, tables and conditions in this case will be selected using a multitude of checkbox's. I want to incorporate any possible search into one button click.
Use sql joins ..Inside your commenttext like select a.row,b.rowtwo from tableone a inner join tabletwo b on a.row = b.row where a.row = your values
You can use the String.Format method
Converts the value of objects to strings based on the formats specified and inserts them into another string.
If you are new to the String.Format method, see the Getting started with the String.Format method section for a quick overview.
So you can use like that
cmd.CommandText = String.Format("Select {0} from {1} where {2}", columns, tables, conditions)

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.

How to display grid view based on the selection of three dropdownlist

I have three dropdown list one for name, other month and other is year values. when I select name in dropdown list grid view display values of selected name. when I select month it has to display according to the month. when I select both name and month it has to display according to that. when I select all the three grid view has to shows the values for that condition.
Now am binding the data for dropdown list and grid view is in code behind file.
How to achieve that?
Guide me for ASPX and C# coding.
You have to create a dynamic function which accepts the parameters as you select the choices from the drop down.
public void BindGridView(string Name, string Month, string year)
{
//logic to fetch the data
}
Then you have to check the parameters are null or not. Based on these results you can put the queries to fetch the data.
I achieve that by using following coding.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sivConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT EMPNAME,CONVERT(VARCHAR(11),SALDATE,113),BAS_SAL,BASPAY,ADJ,DA,HRA,MA,TOT_SAL,EPF,FA,CATUP,NET_SAL from salentry where empname ='" + DropDownList1.SelectedValue + "' or DATEPART(MONTH,saldate)='" + DropDownList2.SelectedValue + "' or DATEPART(YEAR,saldate)='"+DropDownList3.SelectedValue+"'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();`
Do you have idea better than that?

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

How to select different database row base on which radio button selected

I am currently doing a bank project which I could select the months of transaction history I want to view ( Eg: Current Month, Current Month n last 1 month ) Now, I only manage to retrieve all the transaction history I had using grid view. May I know how to view transactions for different period based on the radio button selected? I'm currently using asp.net n C#
myConnection.ConnectionString = strConnectionString;
SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction]", myConnection);
myConnection.Open();
SqlDataReader reader1 = cmd.ExecuteReader();
GridView1.DataSource = reader1;
GridView1.DataBind();
For your SQL command you could try:
SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] where thDate=" + RadioButtonList1.Text + ", myConnection);
Where RadioButtonList1 is replaced by the name of your RadioButtonList. This should place the value of the selected radio button into the SQL statement.

Categories

Resources