sorting filtered data in asp.net listview - asp.net

I've created a listview that's filled up with a list of guitars from the database on page load like so:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["GuitarsLTDBConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT * FROM Guitars", con);
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
DataTable dt = new DataTable();
da.Fill(dt);
lvGuitars.DataSource = dt;
lvGuitars.DataBind();
}
The following code filters that list of guitars by a certain Make when the user checks the checkbox corresponding to that make
protected void chkOrgs_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = (DataTable)lvGuitars.DataSource;
DataView dv = new DataView(dt);
if (chkOrgs.SelectedValue == "Gibson")
{
dv.RowFilter = "Make = 'Gibson' OR Make='Fender'";
}
lvGuitars.DataSource = dv.ToTable();
lvGuitars.DataBind();
}
Now, what I want to do is be able to sort the latest data that is present within the listview. Meaning, if sort is clicked before filtering, the it should sort all data. If sort is clicked after filtering, it should sort the filtered data. I'm using the following
code, which is triggered upon a LinkButton click
protected void lnkSortResults_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)lvGuitars.DataSource;
DataView dv = new DataView(dt);
dv.Sort = "Make ASC";
lvGuitars.DataSource = dv.ToTable();
lvGuitars.DataBind();
}
The problem is that all the data that the listview was loaded with before any filtering is sorted, and not the latest filtered data. How can I change this code so that the latest data available in the listview is the one that's sorted?
Thanks

if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["GuitarsLTDBConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT * FROM Guitars", con);
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, con);
DataTable dt = new DataTable();
da.Fill(dt);
lvGuitars.DataSource = dt;
lvGuitars.DataBind();
ViewState["dt"] = dt;
}
The loading need to be set like this. Access/Update the Viewstate as well on filter and Sorting.

Related

Using Drop Down List to modify a GridView in asp.net

Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
connection db_obj1 = new connection();
SqlConnection sql_obj = db_obj1.Connect();
if (this.DropDownList1.SelectedIndex >= 0)
{
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
// SqlDataReader query_read = query.ExecuteReader();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataTable table = new DataTable();
adapter.SelectCommand = command;
adapter.Fill(table);
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
}
}
The problem is that when I run the code, I only see the drop down list and no GridView even when I select dofferent options. I tried debugging and it seems that the table DOES get filled and the only problem that I think is in the line 'grd.FindControl("GridView1").Is this the proper way to give a gridview a data source?
According to me you should not use like
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
on behalf that try as below
string brand = DropDownList1.SelectedItem.Text;
after that fire a query.
i hope it will halpful.
After Edit now use this code
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataSet ds = new DataSet();
DataTable table;
adapter.SelectCommand = command;
adapter.Fill(ds, "ABC");
table = ds.Tables["ABC"];
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
Explanation
adapter.Fill(ds, "ABC");
here ABC is a temp name of table you can take anything.
table = ds.Tables["ABC"];
and write here same table name as you have taken a temp table name.
now try it.

Asp.Net Datagrid view is not updating on new insertion

Well As the title explains it all so here is the code i used so far
public partial class data : System.Web.UI.Page
{
System.Data.SqlClient.SqlConnection con3;
System.Data.SqlClient.SqlDataAdapter da;
DataSet ds1;
DataTable dt;
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
con3 = new System.Data.SqlClient.SqlConnection();
con3.ConnectionString="Data Source=localhost; initial catalog=test;user id=xx;password=xxxx;";
con3.Open();
ds1 = new DataSet();
SqlCommand cmd3 = new SqlCommand();
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.CommandText = "selectdata";
cmd3.Connection = con3;
da = new SqlDataAdapter (cmd3);
da.Fill(ds1, "abc");
con3.Close();
dt = new DataTable();
dt = ds1.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
Stored Procedure is
Create PROCEDURE [dbo].[selectdata]
AS
BEGIN
select * from data
END
i searched stack overflow & did search on Google but nothing happened.
i tried closing connection after data bind, defining a new data set & creating the table again & much more please help
Try reloading the page after insertion.
The Answer Above just refresh the page so in my view it should be
1--> Define A Function & bind data in this such as
private void bind_data()
{
ASPxGridLookup2.DataSource = dt_employee;
ASPxGridLookup2.DataBind();
ASPxGridLookup3.DataSource = dt_attendance;
ASPxGridLookup3.DataBind();
ASPxGridView1.DataSource = dt_attendance;
ASPxGridView1.DataBind();
}
2--> Call this function whenever you need to refresh the datagrid such as right after insertion
obj2.insertion();
bind_data();

Making code duplication to refresh the gridview in asp.net

I am trying to update the gridview after updating some data. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
con.Close();
}
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = studentLevel.Rows[row];
DataRow dr = ((DataTable)studentLevel.DataSource).Rows[gdrow.DataItemIndex];
string id = dr["ID"].ToString();
Student student = new Student(Convert.ToInt32(id), "", "", "", "", "", "", "");
if (e.CommandName == "Undergraduate")
student.setLevelRole(new UnderGraduateStudent());
else if (e.CommandName == "Graduate")
student.setLevelRole(new GraduateStudent());
student.writeLevelRole(id);
SqlConnection con = new SqlConnection(); //HERE IS DUPLICATION
//refresh the gridview on the page
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
con.Close();
}
The problem is, if i do not write the last 12 lines of the code, which is the same code as page_load method, the gridview does not refresh itself on the page. Waht can i do to avoid this?
Thanks
You should provide a method that loads the data and databinds the GridView, for example DataBindGrid:
private void DataBindGrid()
{
using(var con = new SqlConnection(University.GetConnectionString()))
{
con.Open();
string query = "select [ID],[Name],[Surname],[level] from StudentTable order by ID";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
studentLevel.DataSource = dt;
studentLevel.DataBind();
}
}
Then you can call it from wherever you need. If you want to change something you have only one place to maintain which is less error-prone.
Note that you should databind the GridView only if(!IsPostBack) if you use ViewState(default):
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback))
DataBindGridView();
}
and in RowCommand
protected void studentLevel_RowCommand(object sender, GridViewCommandEventArgs e)
{
// ... update student ... then
DataBindGridView();
}

3tier Architecture for DatagridView

I have a DatagridView and i want to populate it with the contents of a database. I know it can be done through DataAdapter, dataset and Fill/Update commands and all. But what I want to know is, how to write it in a 3tier architecture. I mean, what will be the commands in the Presentation layer, Business layer and Data layer. I am new born baby for 3tier architecturre. And not able to get it right.Thanks.
After googling it for a while and implementing some of my techniques, I came upto this:
UILayer:
private void FillData(object sender, EventArgs e)
{
BusinessObject bo = new BusinessObject();
Datatable dt = new Datatable();
dt = bo.getTable();
datagridview.DataSource = dt;
}
BusinessLayer:
public DataTable getTable()
{
DataLayer dl = new DataLayer();
DataTable dt = new DataTable();
dt = dl.getTable();
if(dt == null || dt.HasErrors == true)
{
MessageBox.Show("Datable has Errors or is Null");
return
}
return dt;
}
DataLayer:
public DataTable getTable()
{
SqlConnection con = new SqlConnection(connectionString);
string myCommand = "Select empId, empDesignation from Employees";
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(myCommand, con);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope it helps.

Asp.net repeater control data duplicated when use multiple times binding

I am using asp.net 2008 repeater control. I am trying to refresh the repeater control when a button is clicked, it shows me duplicated values, that means its appending the same values once again. Here is my code
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString);
String sql;
sql = "select * from FeeCollection Where AdminNo='"+lblstano.Text+"'";
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter(sql, con);
da.Fill(ds, "FeeCollection");
dt = ds.Tables["FeeCollection"];
Repeater4.DataSource = dt;
Repeater4.DataBind();
con.Close();
}
protected void btnMedical_Click(object sender, EventArgs e)
{
LoadRepeater1();
}
I want to remove the existing data and refresh the data instead of appending.
Not sure where ds (DataSet) in instantiated. Try to instantiate the DataSet/DataTable within the LoadRepeater1() method.
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager
.ConnectionStrings["SqlServerConnection"].ConnectionString);
sql = "select * from FeeCollection Where AdminNo=#AdminNo";
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#AdminNo",System.Data.SqlDbType.VarChar,20).Value=lblstano.Text;
da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
Repeater4.DataSource = dt;
Repeater4.DataBind();
}

Resources