SqlDataSource lost the where clause during paging - sql

I have a SqlDataSource with this query:
SELECT [ProductName], [Debscription], [Price] FROM [MyDb] WHERE ([Date1] >= #Date1) ORDER BY [ProductName]">
When I load the page, it works fine and shows me only the products that I want.
When I try changing page of the GridView, and for example, go to page 2, it refreshes the page and generates lots of page indexes as the where clause is lost.
How can I solve this?
I thought that the statement was automatically saved, but it's not.
How can I save the where clause during paging?

For dynamic paging you should use an ObjectDataSource instead of a SqlDataSource.

If you want the grid to handle paging, bind it to a DataTable or DataSet. For ex:
private void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
BindData();
}
private void BindData()
{
// Connect to the Database
SqlConnection myConnection = new SqlConnection(connection string);
// Retrieve the SQL query results and bind it to the DataGrid
string SQL_QUERY = "SELECT ProductName, UnitPrice, UnitsInStock " +
"FROM Products";
SqlCommand myCommand = new SqlCommand(SQL_QUERY, myConnection);
// Use a DataTable – required for default paging
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataTable myTable = new DataTable();
myAdapter.Fill(myTable);
dgProducts.DataSource = myTable;
dgProducts.DataBind();
myConnection.Close();
}
https://msdn.microsoft.com/en-us/library/aa479006.aspx

Related

How to bind DevExpress XtraReport by Query String

Can anybody tell me how I can bind a DevExpress XtraReport by Query String?
I want to show only the ID value of 8 in the report, I am using a store procedure to get data.
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("GetLabReport", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#PID", SqlDbType.Int).Value = Request.QueryString["ID"].ToString();
connection.Open();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
XtraReport1 Rept = new XtraReport1();
string path = (Server.MapPath("App_Code/XtraReport1.cs"));
DA.Fill(DT);
connection.Close();
if(DT.Rows.Count>0)
{
}
The above works fine with Crystal Reports but not with DevExpress XtraReports.
I suggest you to create report parameters and then set the parameter value using the query string.
See the comments on below thread:
Report Designer using SQL Server Stored Procedure as data source, generates .Net exception.
Add a Report's Parameters and then map it to your query parameter. Then pass the value from Request.QueryString to the Parameter.Value property
Example:
protected void Page_Load(object sender, EventArgs e) {
XtraReport3 report = new XtraReport3();
report.Parameters[0].Value = Request["MyParam"];
ASPxDocumentViewer1.Report = report;
}
References:
Passing querystring values to a report
How to use parameter from querystring to show report
Parameters support thru URL QueryString in XtraReports?
How to pass QueryString parameter into Report (master-detail) c#

Get SQL data via listbox

Ok, so what I am trying to do is click one item in a listbox that i have, that listbox gets data from the sql database depending on that the user types into the textbox.
Now when I click that item in the first listbox, I need more info related to that item to show up in the 2nd list box.
When the user enters a name in the textbox, the first 10 in sql show up, now that I have that, I need to click on one of the items and get the 'task' of that client in the next listbox. Task is MATTERS in the database.
I am pretty sure that my code is correct, I get no errors but nothing shows up in the list box.
Here is my code:
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
if (listBox1.ContainsFocus)
{
if (item == "")
{
}
else
{
var con2 = Conn.ConnString();
using (SqlConnection myConnection2 = new SqlConnection(con2))
{
string oString2 = "select CLIENTMATTERS.MATTER, CLIENTMATTERS.DESCRIPTION from CLIENTMATTERS join CLIENTCODES on CLIENTMATTERS.CLIENT = CLIENTCODES.CLIENT Where CLIENTCODES.DESCRIPTION = '#code1'";
SqlCommand oCmd = new SqlCommand(oString2, myConnection2);
oCmd.Parameters.AddWithValue("#code1", item);
myConnection2.Open();
oCmd.Connection.Open();
List<string> codelist2 = new List<string>();
using (SqlDataReader oReader2 = oCmd.ExecuteReader())
{
if (oReader2.HasRows)
{
string value = string.Empty;
while (oReader2.Read())
{
codelist2.Add(oReader2["MATTER"].ToString());
}
}
}
this.listBox2.DataSource = codelist2;
}
}
}
}
You need to use BindingList<> instead of List<>.
The List<> doesn't implement the ListChanged event, so the ListBox doesn't get notified when the datasource changes.
In your example it would look like this:
BindingList<string> codelist2 = new BindingList<string>();
For further information take a look at
BindingList on MSDN.

Petapoco: How to databind gridview using join from two tables?

I dont want to do using a custom class.
var q = db.Query<dynamic>(query); //This does not work
query has joins and custom created columns from multiple tables.
You can check the PetaPoco.cs "ExecuteReader" method to see if it looks something like this(see code below):
my file did not have any code in the function so I model it after Execute scalar method.
this will return a generic DataTable that is perfectly bindable to datagrid.
however keep in mind that to make any changes to the data you will need to implement
your own CRUD methods as the resulting DataTable is readonly.
//Execute Reader
public DataTable ExecuteReader(string sql, params object[] args)
{
try
{
OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sql, args))
{
var val = cmd.ExecuteReader();
OnExecutedCommand(cmd);
var dt = new DataTable();
dt.Load(val);
return dt; //(T)Convert.ChangeType(val, typeof(T));
}
}
finally
{
CloseSharedConnection();
}
}
catch (Exception x)
{
OnException(x);
throw;
}
}
public DataTable ExecuteReader(Sql sql)
{
return ExecuteReader(sql.SQL, sql.Arguments);
}
Create a class that contains the fields from the two tables you want to display in the grid.
Populate your query with a SQL statement that joins the tables and returns the columns you need.
Then
var q=db.Query<YourClassName>.Query(query)
should work.
You can create a database view, and then the T4 templates will automatically generate the class for that. You need to add
IncludeViews = true;
to Database.tt

Why calling DataTable.Clear() then DBDataAdapter.Update(DataTable) does not clear the table in database?

I try to use the code sample in DBDataAdapter.Update Method to clear a table in a database.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM WebCam", connection);
DataTable table = new DataTable();
adapter.Fill(table);
table.PrimaryKey = new DataColumn[] { table.Columns["Date"] };
//table.Rows[0]["Date"] = System.DateTime.Now; //It's OK to modify a row
table.Clear(); //But it is not working to clear the table
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(table);
}
I can add new rows or modify existing rows, and the changes can be committed to the database, but if I try to empty the table, the change to 'table' can not be committed to the database, also, no exception is thrown.
Do I miss something?
u should get error on this line:
table.PrimaryKey = new DataColumn[] { table.Columns["Date"] };
this would mean that u have catched the exception somewhere else, maybe from where the function is being called, and not showing the error in a messege box.
Another reason might be because you are using words like Table, adapter etc ... my guess is that you might be overloading some reserved words functionalities.

Reading and Updating Data Using SqlDataAdapter Question

I'm looking for some examples on how to best use SqlDataAdapter to access and update data in my application.
Right now I have something like this:
SqlDataAdapter adapter;
DataSet myData = MyDataAccessClass.GetData("Select * from Students", ref adapter);
// change some data here and save changes
adapter.Update();
All of this occurs in code behind, and I dont really like it at all.
So, I'm trying to find a way to do something like this:
DataSet myData = MyDataAccessClass.GetStudents();
// change some data and save changes
MyDataAccessClass.SaveStudents(myData);
Where SaveStudents method still uses SqlDataAdapter to update db.
Any ideas on how to make this work or some pointers to best practices of doing
something like this are highly appreciated. Thank you.
That seems like a fairly basic Data Access Layer implementation, to me. Generally, I do it something like this:
public class MyDataAccessClass
{
private string ConnString;
public MyDataAccessClass()
{ //Get connection string from configuration file }
public MyDataAccessClass(string connString)
{ ConnString = connString; }
public DataSet GetAllStudents()
{
//your SQL Adapter code here...
}
}
One note that I'd make is that with so many ORM solutions (including just Entity Framework and Linq2Sql) available, you may want to consider using collections of objects instead of data-sets for your Data Representations. Then you can have a method like:
public void CreateUpdateStudent(Student student)
{
//update database
}
That's fairly subjective, I'll admit, but I find it preferable to using straight DataSets.
If you want to get update data using the sql-data-adapter then you could use these
Using System.Data.SqlClient;
SqlConnection con = new SqlConnection("Data Source=abcd-pc;Initial Catalog=user_info;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
try
{
da.UpdateCommand = new SqlCommand("Update logindemo set password=#pswd where username=#uname",con);
da.UpdateCommand.Parameters.Add("#pswd", SqlDbType.VarChar).Value = txtpass.Text;
da.UpdateCommand.Parameters.Add("#uname", SqlDbType.VarChar).Value = txtusername.Text;
con.Open();
da.UpdateCommand.ExecuteNonQuery();
Label1.Text = "Data Updated";
con.Close();
}
catch
{
Label1.Text = "Unable To Connect";
}
I hope you understand how to update the data easily. It just like the example. You can use these type of example in Inserting into the Data, and Deleting the Data with using specific the command and sql query as it required.