I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..
Related
I've bound three drop down lists with same oledb data adapter. this oledbdataadapter fills three different datatables which I use eventually to fill up three dropdowns. But when I access three dropdown values in submit button, all three dropdowns give same selected item even when I've selected three different options in dropdowns. Can Anybody help?
here's my code:-
//oda - oledbdataadapter
oda.SelectCommand = cmdExcel;
oda.Fill(dt_Temp);
DataTable dt_costcode = new DataTable();
oda.Fill(dt_costcode);
DataTable dt_desc = new DataTable();
oda.Fill(dt_desc);
DataTable dt_unit = new DataTable();
oda.Fill(dt_unit);
connExcel.Close();
ViewState["TempImport"] = dt_Temp;
List<CostColumns> list_costCode = Columns(dt_costcode);
Bind_ddlCostCode(list_costCode);
List<CostColumns> list_desc = Columns(dt_desc);
Bind_ddlDescription(list_desc);
List<CostColumns> list_unit = Columns(dt_unit);
Bind_ddlUnitofMeasure(list_unit);
here code for binding Dropdowns:-
public void Bind_ddlCostCode(List<CostColumns> list_costCode)
{
foreach (CostColumns costcol in list_costCode.ToList())
{
if (costcol.ColumnType == "System.String")
{
ddlCostCodeNumber.Items.Add(new ListItem(costcol.Columns, costcol.ColumnType));
}
}
ddlCostCodeNumber.DataBind();
ddlCostCodeNumber.Items.Insert(0, new ListItem("--Select CostCode--", "0"));
}
public void Bind_ddlDescription(List<CostColumns> list_desc)
{
foreach (CostColumns costcol in list_desc.ToList())
{
if (costcol.ColumnType == "System.String")
{
ddlDescription.Items.Add(new ListItem(costcol.Columns, costcol.ColumnType));
}
}
ddlDescription.DataBind();
ddlDescription.Items.Insert(0, new ListItem("--Select Desc.--", "0"));
}
//(Same code for Bind_ddlUnitofMeasure(list_unit))
And here's where It all goes wrong:-
protected void Btn_ImportRecords_Click(object sender, EventArgs e)
{
DataTable dt_Temp= (DataTable)ViewState["TempImport"];
DataTable dt_Import = new DataTable();
Int32 i = costCodeNo();
string ccn = ddlCostCodeNumber.SelectedItem.Text;//gives same selected option(CostCodeNumber)
string desc = ddlDescription.SelectedItem.Text;//gives same selected option
string unit = ddlUnitofMeasure.SelectedItem.Text;//gives same selected option
dt_Import.Columns.Add(new DataColumn("CostCodeNo", typeof(Int32)));
dt_Import.Columns.Add(new DataColumn(ddlCostCodeNumber.SelectedItem.Text, typeof(string)));
dt_Import.Columns.Add(new DataColumn(ddlDescription.SelectedItem.Text, typeof(string)));
//throws exception that dt_Import already has same column name
}
After I get the value show in GridView the DropDownList will contain duplicate items when I click again.
public void Page_Load(object sender, EventArgs e)
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
public void button_click(object sender, EventArgs e)
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
You should write it as:
public void Page_Load
{
if (!IsPostBack){
string sql = "select distinct cproject from I.dd.project";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
con.Close();
}
}
public void button_click
{
sqldataadapter da = new sqldataadapter(Select * from lalala where id = '"+dropdownlist.item.selectedvalue.tostring()+"')
+"where A.cproject ='"+DropDownList1.SelectedValue.ToString()+"', con);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
The Page_Load method is called each time a postback occurs (such as when you click on an ASP.NET button control). The data was already added on the first load and stored in ViewState. On the second request, it adds it again. You can detect whether you're in a postback by using the Page.IsPostBack property.
public void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// add items to drop down list
}
}
Side note, make sure that any objects that implement the IDisposable interface are handled properly. You need to make sure they're disposed when you're done with them to avoid hard to diagnose errors. You can either call .Dispose() on them in a finally block or you can wrap them in a using statement. Your SqlCommand, SqlConnection (this should not be a property/field)andSqlDataReaderall implementIDisposable`.
I just found the solution. Put the if(!Ispostback) in the page load statement there.
At best-guess, without compile-able code, it looks like your Dropdown List is persisted between page loads, meaning it's never going out of context (the object remains in memory). So, it is just getting appended over and over each time there is a page load. You probably want to do a check for existing values:
public void Page_Load()
{
string sql = "select distinct cproject from I.dd.project";
con.Open();
using(SqlCommand cmd = new SqlCommand(sql, con)) {
using(SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read())
{
//Have not tested the if statement... may need to correct it.
if(!DropDownList1.Items.Contains(dr[0].ToString())) {
DropDownList1.Items.Add(dr[0].ToString());
}
}
}
}
con.Close();
}
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);
}
}
Trying to remove duplicate treenodes when adding data from sql server.
Data is added to tree ok but I can't seem to work out how to remove duplicates of the parent nodes.
public partial class SYS_Main : System.Web.UI.Page
{
public TreeNode testerr = new TreeNode();
private List<string> _isdupe = new List<string>();
private List<string> _dupe = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
PopulateRootLevel();
TV_Test.CollapseAll();
}
private void PopulateRootLevel()
{
const string connectionString = ("user=;" +
"password=;server =UsersSQL;" +
"Trusted_Connection=yes;" +
"database=System Details; " +
"connection timeout=30");
// connects to sql DB
// sql connection
SqlConnection objConn = new SqlConnection(connectionString);
// sql queries to server
SqlCommand objCommand = new SqlCommand("SELECT Contract, [Server Name],[IP Address] FROM tblServers where Contract !='' AND [SERVER NAME] !='';", objConn);
SqlCommand testquery = new SqlCommand("select s.contract ,COUNT(*)from [System Details].dbo.tblServers s where contract !='' group by Contract having count (*)>1 ;", objConn);
// data adapater holds values of sql queries
SqlDataAdapter da = new SqlDataAdapter(objCommand);
// datatable to hold query data into nodes
DataTable dt = new DataTable();
// data table populated
da.Fill(dt);
//Calls popnodes method and includes dt + nodes for
PopulateNodes2(dt,TV_Test.Nodes);
}
//pop nodes method
private void PopulateNodes2(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TV_Test.Nodes.Clear();
TreeNode IP = new TreeNode();
IP.Text = dr["IP Address"].ToString();
// new instance of a treenode
testerr = new TreeNode();
testerr.Text = dr["Server Name"].ToString();
testerr.ChildNodes.Add(IP);
TreeNode parent = new TreeNode("Text1");
parent.Text = "keyText1";
parent.Text = (dr["Contract"]).ToString();
_isdupe.Add(parent.Text);
parent.ChildNodes.Add(testerr);
nodes.Add(parent);
string trued;
trued = _isdupe.Distinct().ToString();
if (trued.Equals(parent.Text))
{
TV_Test.Nodes.Remove(parent);
}
else
{
}
}
}
}
}
I think your algorithm is wrong, if you order your query you'll be able to fill the treeview with no duplicate directly.
I am using Visual studio and have the following page_load function on my Default.aspx web form:
if (IsPostBack == false)
{
//Display all records on the form load
DisplayCars("");
I have a user, where I can get their username (which I have used to add as the "Creator" of the specific data record). I want to use this username to only display cars where the username = ACar.Creator
How would I go about doing this? I have everything setup in order to do this.
I need something like the following:
if (User.Identity.Name == ACar.Creator) {
show this record
}
But I do not know the syntax for this within aspx/sql
Thanks
You should actually do this in the database by passing username
public DataTable GetUserRecord(string userName)
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection("connection string to database");
using(conn)
{
string sql = "SELECT car.CarName, car.Model FROM car WHERE car.Creator = #UserName";
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.AddWithValue("#UserName", userName);
dt.Load(comm.ExecuteReader());
}
return dt;
}
From your page
protected void Page_Load(object sender, Eventargs e)
{
DataTable dt = GetUserRecord(User.Identity.Name);
if(dt.Rows.Count > 0)
{
string firstRowCarName = dt.Rows[0]["CarName"];
//etc
}
}