3tier Architecture for DatagridView - 3-tier

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.

Related

setting a dropdownlist value from database on page load

Sounds like an easy job but havent been able to figure it out.I have an edit profile page where all the user data is pulled from database to respective textboxes,labels etc on Page_Load.The dropdownlist is binded to a table as below.My ddl is as below :
<asp:DropDownList ID="ddlGender" runat="server" Width="160px" AutoPostBack="True" OnDataBound="ddlGender_DataBound">
</asp:DropDownList>
and is binded as below :
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
I am not able to set a value in the dropdownlist though.Here is what I have done :
private void ExtractData()
{
string CS = ConfigurationManager.ConnectionStrings["fgff"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
But it says 'Object is not set to an instance'. So i played around a bit and tried doing it in DataBound like this :
protected void ddlGender_DataBound(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
Now it doesnt throw any error and it doesnt select the value as well.
PS : 1.I have set Autopostback true for the ddl.
2.I am aware of sqlInjection and have made changes to make it look simpler.
My final PageLoad looks like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
ExtractData();
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
}
if (hfImagePath.Value == "" || hfImagePath.Value == "0")
{
imgCropped.ImageUrl = "~/ProfilePictures/DefaultProfilePicture.png";
hfImagePath.Value = "0";
}
else
{
imgCropped.ImageUrl = "~/ProfilePictures/" + hfImagePath.Value;
}
//lblRegistration.Text = Session["Button"].ToString();
}
For one, you are calling ExtractData before you have actually bound the DropDownList in the BindGenderDropDown method. This means that your dropdown will have no items when you try to look it up and set the selected item. First things first you need to move the databinding code above ExtractData.
Second, you are you trying to set the selected value in an unusual way. Instead of attempting to FindByText you should try setting SelectedValue instead.
I will assume that the contents of rdr["Gender"] in ExtractData is the GenderId you have bound to the dropdown, and not the display value in GenderName. I will also assume that GenderId is M and F and GenderName is Male and Female (although if your actual implementation varies slightly then that's ok).
Try changing:
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
To:
ddlGender.SelectedValue = rdr["Gender"].ToString();
Also be sure to remove the code you have added for the DataBound handler, it is not necessary here.
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
You are trying to set the value to a specific Column, yet you are binding it to a DataSet and not a DataTable. (A DataSet has no columns only DataTables).
Try the following assuming the DataSet has a table returned and the column names match your table structure:
string strDesiredSelection = "Male";
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds.Tables[0];
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
foreach(ListItem li in ddlGender.Items){
if(li.Value.Equals(strDesiredSelection)){
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(li);
}
}

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.

How to pass a Session to a DataTable?

In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}

sorting filtered data in asp.net listview

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.

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