How to update a datasource dynamically C#? - c#

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.

Related

parameterized query using textbox as a filter

On a CRM Database I have a form with all the clients details (from PostgreSQL)
and underneath it there is a datagrid I need filled with all the data about visit to the client whose details are currently displayed above.
I can't find a way to filter the data in the datagrid according to one of the text boxes in the details view.
I tried to create a parameterized query with:
SELECT
WHERE client_code = #client_code
but it just gives me
Error in WHERE clause near '#' Unable to parse query text.
also I have no idea how to define the #client_code parameter.
if I understand correct you are trying to run the query without defining the parameter #client_code. Try:
SqlCommand cmd = new SqlCommand("SELECT <FIELD_NAME1>,<FIELD_NAME2.. FROM <TABLE_NAME> WHERE client_code = #client_code", con);
con.Open();
cmd.Parameters.AddWithValue("#client_code", myTExtbox.Text);
DataTable dt = new DataTable();
using (SqlDataAdapter da=new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
myDatGrid.DataSource=dt;

Error with databound DataGridView Display Textbox's Text

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;
}
}

Displaying selected data in a datagridview

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 +"'";

Asp.Net Application Properly using .RowFilter to Textbox

In the application im writing im connecting to a SQL database, then using an Adapter to hold the returned results but now I want to filter the results with .RowFilter three times return the filtered result each time to Textbox. I'm not sure if this is best executed with an if statement or with some Switch statement. Heres the code for a better idea of what im trying to do.
using (con)
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDnumber);
//SQLConnection Established and Opened
SqlDataAdapter adapter = new SqlDataAdapter(selectSQL, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
//Adapter Created and Filled
DataView dvQ = dt.DefaultView;
dvQ.RowFilter = "AccountType = Q";
QualVol.Text = "TotalVolume".ToString();
//First Filter then Change QualVol textbox text to Column data TotalVolume
dvQ.RowFilter = "AccountType = N";
NonVol.Text = "TotalVolume".ToString();
//Filter original DataView then Change NonVol textbox text to Column data TotalVolume
dvQ.RowFilter = "AccountType = M";
MidVol.Text = "TotalVolume".ToString();
//Filter original DataView then Change NonVol textbox text to Column data TotalVolume
}
As per dotnetperls performance of a switch is better than an if but also gives a good clue on what situation an if performs better than the switch
http://www.dotnetperls.com/if-switch-performance

Bind DataGridView To Results of Access SQL Query String

I would like to bind a DataGridView to the results of a query generated as text at runtime.
How can I send a query as text to Microsoft Access and bind the results to the DataGridView?
When the user clicks the button (ok_btn), I want the contents of the textbox (query_txt.Text) sent to Microsoft Access, then I want the results of the query shown in my DataGridView (results_grid).
Simple one-row queries are fine for now: (SELECT "a";, SELECT "a", "b";, SELECT now();)
NOTE: C# accepted, VB.NET preferred
using System.Data.OleDb;
OleDbConnection conn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0;User Id=;Password=;Data Source=" + fileName);
conn.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query_txt.Text, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView.DataSource = ds.Tables[0];
conn.Close();
Note: query_txt.Text is the Query that you want to run. fileName is the path to where your file is stored.

Categories