I have codes here that display all data in access database. Is it possible to only display specific or selected data from my database?
here is my code :
string connStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\SISC-STRONGHOLD\MIS!\wilbert.beltran\SEEDBucksDbase.accdb";
string query = "SELECT * From TableAcct";
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Columns["UserPassword"].Visible = false;
}
conn.Close();
}
thanks! :)
To query for a last name (assuming the column in the table is called LastName), try this:
string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";
Of course, you have to be careful of SQL Injection attacks. I'm not familiar with using paramaterized queries in Access.
Is this a public form, or internal just for you (or trusted users)?
you just need to write down where condition in you query will do work for you,
Following is example of it
string query = "SELECT col1,col2 From TableAcct where col1=value";
This will fetch data that satisfy you condition and bind with the grid control.
And instead of * in select list give name of the columns you want to display.
for getting value form control like textbox
string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";
Note- make use of sqlparameter to avoid SQLInjection , above is just an example.
string query = "SELECT (SelectedColumnNames) From TableAcct Where LastName=(LastName)";
INstead of Searching with a * in a Query enter the desired columns for ex:-
string query = "SELECT phno,address,FirstName From TableAcct where LastName ='"+txt1.text +"'";
Related
Hie I'm new to ASP.Net and needed some help.
Here is my problem: I have 4 drop downs in my application, a button saying search, grid view to show the results. I was trying to filter the results based on the value of drop downs.
So i wrote the query as "select * from table where column1=dd1.SelectedItem.Value" but the tricky part is i want the results to be displayed even if one of the drop down is selected or two of them is selected or all of them is selected. How do i write the Where Part in my SQL query?? I know that I have to use dynamic SQL but i have no clue about dynamic SQL.
Use something like this
string q = #"
SELECT * FROM table
WHERE
(#value1 IS NULL OR column1 = #value1)
AND
(#value2 IS NULL OR column2 = #value2)
AND
(#value3 IS NULL OR column3 = #value3)
";
var command = new SqlCommand();
command.CommandText = q;
command.Parameters.AddWithValue("#value1", dd1.SelectedItem.Value);
command.Parameters.AddWithValue("#value2", dd2.SelectedItem.Value);
command.Parameters.AddWithValue("#value3", dd3.SelectedItem.Value);
First you should store dd1.SelectedItem.Value in a variable as
string v = dd1.SelectedItem.Value.ToString();
then create a string for your query as
string q = "select * from table where (column1 is null or column1=" + v + ")";
then use this code:
SqlCommand com = new SqlCommand(q, yoursqlconnection);
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
I have calender that displays inforamtion based on the date selected.
It is something like this:
string queryString = "SELECT * from events";
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = queryString;
SqlDataReader reader = thisCommand.ExecuteReader();
if(true)
queryString = "SELECT Text from events where repeat = 1";
else
queryString = "SELECT Text from events where repeat = 0";
GridView1.DataSource = reader ;
GridView1.Bind();
The error I am getting is "The data source does not support server-side data paging"
You should use SqlDataAdapter instead to fill DataTable and then use the datatable as datasource for your gridview. SqlReader is class for fast access to sql data and it isn't suitable as datasource.
var adapter = new SqlDataAdapter(thisCommand);
var table = new DataTable();
adapter.Fill(table);
GridView1.DataSource = table;
GridView1.Bind();
You'll be doing all sorting/paging on web server though - this operations are best handled directly on SQL server. So I suggest using ObjectDataSource or LinqDataSource and adjusting the queries appropriately to handle SQL-server-level paging/sorting.
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;
}
}
I want to be able to execute a custom SQL query against a table adapter that I have. Is it possible to do this? Or can I only use the predefined queries on each table adapter in the dataset design view?
If I can't do this, how would I go about executing my SQL query against a table, and having the results display in my datagridview that's bound to a table adapter?
Thanks.
EDIT: I didn't explain myself properly. I know how to Add queries to a tableadapter using the dataset designer. My issue is i need to execute a custom peice of SQL (which i build dynamically) against an existing table adapter.
I posted a comment pointing to an example using VB which creates a class that extends TableAdapter. Instead of using the VB example and rewriting it in C# I will show how this can be done without creating a class that extends TableAdapter.
Basically create a BackgroundWorker to perform the sql query. You don't have to but it would be nice. Build the query string based on input from the user.
private void queryBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Initialize sqlconnection
SqlConnection myConnection;
//Convert date in to proper int format to match db
int fromDate = int.Parse(dateTimePickerStartDate.Value.ToString("yyyyMMdd"));
int toDate = int.Parse(dateTimePickerEndDate.Value.ToString("yyyyMMdd"));
//Setup Parameters
SqlParameter paramFromDate;
SqlParameter paramToDate;
SqlParameter paramItemNo;
SqlParameter paramCustomerNo;
//Fill the data using criteria, and throw any errors
try
{
myConnection = new SqlConnection(connectionString);
myConnection.Open();
using (myConnection)
{
using (SqlCommand myCommand = new SqlCommand())
{
//universal where clause stuff
string whereclause = "WHERE ";
//Add date portion
paramFromDate = new SqlParameter();
paramFromDate.ParameterName = "#FromDate";
paramFromDate.Value = fromDate;
paramToDate = new SqlParameter();
paramToDate.ParameterName = "#ToDate";
paramToDate.Value = toDate;
myCommand.Parameters.Add(paramFromDate);
myCommand.Parameters.Add(paramToDate);
whereclause += "(TableName.date BETWEEN #FromDate AND #ToDate)";
//Add item num portion
if (!string.IsNullOrEmpty(itemNo))
{
paramItemNo = new SqlParameter();
paramItemNo.ParameterName = "#ItemNo";
paramItemNo.Value = itemNo;
myCommand.Parameters.Add(paramItemNo);
whereclause += " AND (Tablename.item_no = #ItemNo)";
}
//Add customer number portion
if (!string.IsNullOrEmpty(customerNo))
{
paramCustomerNo = new SqlParameter();
paramCustomerNo.ParameterName = "#CustomerNo";
paramCustomerNo.Value = customerNo;
myCommand.Parameters.Add(paramCustomerNo);
whereclause = whereclause + " AND (Tablename.cus_no = #CustomerNo)";
}
string sqlquery = "SELECT * FROM TableName ";
sqlquery += whereclause;
//MessageBox.Show(sqlquery);
myCommand.CommandText = sqlquery;
myCommand.CommandType = CommandType.Text;
myCommand.Connection = myConnection;
this.exampleTableAdapter.ClearBeforeFill = true;
this.exampleTableAdapter.Adapter.SelectCommand = myCommand;
this.exampleTableAdapter.Adapter.Fill(this.ExampleDataSet.ExampleTable);
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I personally like the idea of coding a class that extends TableAdapter but this was a quick easy way of answering the OP's question. Sorry it took a year :)
Taken from here
To add a query to a TableAdapter in the Dataset Designer
Open a dataset in the Dataset Designer. For more information, see How to: Open a Dataset in the Dataset Designer.
Right-click the desired TableAdapter, and select Add Query.
-or-
Drag a Query from the DataSet tab of the Toolbox onto a table on the designer.
The TableAdapter Query Configuration Wizard opens.
Complete the wizard; the query is added to the TableAdapter.
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)