Show Table when SelectedValue of DropDownList is true C# - c#

I want to show a table when a SelectedValue of my DropDownList ddlKlasse is true. I'm using asp.net empty web forms with a masterpage.
The idea is:
when ddlKlasse.SelectedValue = "2" table tblDubbelTwee must be shown
when ddlKlasse.SelectedValue = "5" table tblVierMet must be shown
when ddlKlasse.SelectedValue = "9" table tblAchtMet must be shown
I get the values in my dropdownlist from my database.
The code I have now is:
In my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownListKlasse();
BindDropDownListVereniging();
if (!Page.IsPostBack)
{
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
}
}
For binding the dropdown:
private void BindDropDownListKlasse()
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT DISTINCT AantalDeelnemers, Naam FROM Klasse;";
com.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
ddlKlasse.DataSource = dt;
ddlKlasse.DataValueField = "AantalDeelnemers";
ddlKlasse.DataTextField = "Naam";
ddlKlasse.DataBind();
conn.Close();
//Adding "Kies de klasse" optie in dropdownlist voor validatie
ddlKlasse.Items.Insert(0, new ListItem("Kies de klasse", "0"));
}
}
}
catch
{
}
}
For showing the tables:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedListItemDubbelTwee = ddlKlasse.Items.FindByValue("2");
if (selectedListItemDubbelTwee != null)
{
selectedListItemDubbelTwee.Selected = true;
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemVierMet = ddlKlasse.Items.FindByValue("5");
if (selectedListItemVierMet != null)
{
selectedListItemVierMet.Selected = true;
tblVierMet.Visible = true;
tblDubbelTwee.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemAchtMet = ddlKlasse.Items.FindByValue("9");
if (selectedListItemAchtMet != null)
{
selectedListItemAchtMet.Selected = true;
tblAchtMet.Visible = true;
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
};
}
My DropDownList:
<div class="form-inline">
<div class="form-group">
<asp:DropDownList ID="ddlKlasse" class="form-control" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlKlasse_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
One of my tables:
<asp:Table ID="tblDubbelTwee" runat="server" class="table">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Naam</asp:TableHeaderCell>
<asp:TableHeaderCell>Email</asp:TableHeaderCell>
<asp:TableHeaderCell>Lidmaatschapsnr</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
But when I run my project and select a field in my DropDownList it gives the error: System.Web.HttpException: Selecting multiple items in a DropDownList is not allowed.
Can you please help me to solve this problem?

Your current handler for DDL index change is doing something very different from what you have described. It basically checks if the list item exists in the ddl list (no matter selected or not) and then tries to select it. Since all of 3 items exist, you are effectively trying to select 3 items, which is not allowed.
What you might be looking for is a switch by selected value:
switch (ddlKlasse.SelectValue)
{
case "2":
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
break;
case "5": //similar here
case "9": //similar here
default:
// exception or something
}

refere this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select DISTINCT Class from addmitionform1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlclass.DataSource = ds;
ddlclass.DataTextField = "Class";
ddlclass.DataValueField = "Class";
ddlclass.DataBind();
ddlclass.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
string id = (ddlclass.SelectedValue.ToString());
con.Close();
SqlDataAdapter da1 = new SqlDataAdapter("Select id,FirstName from addmitionform1 where Class= '" + id + "'", con);
//SqlDataAdapter da1 = new SqlDataAdapter("Select * from addmitionform1 ", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}

First move BindDropDownListKlasse() and BindDropDownListVereniging() inside if (!IsPostBack), as HarveySpecter suggested.
And change ddlKlasse_SelectedIndexChanged() to:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
bool showDubbelTwee = false, showVierMet = false, showAchtMet = false;
switch (ddlKlasse.SelectedValue)
{
case "2":
showDubbelTwee = true;
break;
case "5":
showVierMet = true;
break;
case "9":
showAchtMet = true;
break;
}
tblAchtMet.Visible = showVierMet;
tblDubbelTwee.Visible = showDubbelTwee;
tblVierMet.Visible = showVierMet;
}
What you are doing now in ddlKlasse_SelectedIndexChanged() is check for each value if it's present in the dropdown, and if present select it and show the respective table.
Instead, you need to check which value is selected and show the respective table.

Related

dynamically add itemplate to the gridview

I have created gridview. Added a textbox to specify what number of columns user want to add to the grid dynamically and its done successfully.
I want to add text box to the dynamically added fields to enter the data and save it to the database(I am able to add text fields to the rows and save data) but i didnt got any solution yet.
I have tried with itemplate but I don't know much about it. i have added my code below.
Here is my aspx code
<input type="hidden" runat="server" value="0" id="columnAdded"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:TemplateField HeaderText="S. No.">
<ItemTemplate>
<asp:Label ID="lblsno" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Parts" DataField="parts">
</asp:BoundField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
and here is .cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
drpstation.Items.Clear();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "stationdesc");
drpstation.DataSource = ds.Tables[0];
drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
drpstation.DataBind();
drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
}
catch (Exception ex)
{
string Msg = "select station error";
Msg += ex.Message;
}
finally
{
con.Close();
}
}
if (!IsPostBack)
{
griddisplay();
}
}
public void griddisplay()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
//DataTable dt = new DataTable();
//dt.Columns.Add("Parts", typeof(string));
//DataRow drr = dt.NewRow();
//drr["Parts"] = "Weldmet";
//dt.Rows.Add(drr);
//drr = dt.NewRow();
//drr["Parts"] = "MFG Parts";
//dt.Rows.Add(drr);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
catch (Exception d)
{
string message = "grid error";
message += d.Message;
}
finally
{
con.Close();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
GridView1.Columns.Add(test);
TextBox txtname = new TextBox();
string txtunit = "txtunit";
txtname.ID = txtunit + i;
}
griddisplay();
columnAdded.Value = (addedColumn + num).ToString();
}
public class TemplateHandler : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
TextBox txtbox = new TextBox();
txtbox.Text = "test";
txtbox.DataBinding += Txtbox_Binding;
container.Controls.Add(txtbox);
}
private void Txtbox_Binding(object sender, EventArgs e)
{
//throw new NotImplementedException();
TextBox txttest = (TextBox)sender;
GridViewRow container = (GridViewRow)txttest.NamingContainer;
//txttest.Text = ((TableNameClass)container.DataItem).SkillText;
((DataRowView)container.DataItem)["SkillText"].ToString();
}
}
Please help
Just a pseudo/sample code(not tested!) based on the code you posted, to give you some heads-up
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
GridView1.Columns.Add(test);
// ... Other code as you need
}
}
Hope this help you.

Textbox value doesn't change on button click event in asp.net C#

I'm stuck with a problem where i can't get the values of any control not just textboxes in button click event so here is the scenario, You can skip it and just can look into my button click event
Page product is performing 2 operations
Create
Update
When a user clicks Edit on GridView in updpage It will redirects it to Product Page to update, Same page is performing Create product operation too, So when I receive QueryString value I'll update the product table and when I won't so I just perform Create operation.
Now I'm stuck when there is no QueryString value so textboxes are updating with a new values but when there is, so they don't give me a new value.
Here is my code
On pageLoad Event I'm filling text boxes with there respective values
where there is an update operation
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
}
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Button event code
protected void btn_Insert_Click(object sender, EventArgs e)
{
getpicture();
SqlCommand cmd;
string pathimage ="";
if (pathimage == "")
{
pathimage = product_image.ImageUrl;
}
else
{
pathimage = ViewState["pathimage"].ToString();
}
if (Request.QueryString["update"] != null)
{
int id = int.Parse(Request.QueryString["update"]);
string query = "UPDATE Products SET product_name=#PRODUCTNAME,price=#PRIZE,unit=#UNIT,product_image=#IMAGE,available=#AVAILABLE,product_category=#CATEGORY,product_brand=#BRAND,product_achv=#ACHIV WHERE id = #ID";
cmd = new SqlCommand(query);
txt_name.Text = "";
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
cmd.Parameters.Add("#ID", id);
param.InsertUpdateData(cmd);
}
else
{
string query = "INSERT INTO Products(product_name,price,unit,product_image,available,product_category,product_brand,product_achv) VALUES(#PRODUCTNAME,#PRIZE,#UNIT,#IMAGE,#AVAILABLE,#CATEGORY,#BRAND,#ACHIV)";
cmd = new SqlCommand(query);
cmd.Parameters.Add("#PRODUCTNAME", txt_name.Text);
cmd.Parameters.Add("#PRIZE", txt_price.Text);
cmd.Parameters.Add("#UNIT", txt_unit.Text);
cmd.Parameters.Add("#IMAGE", pathimage);
cmd.Parameters.Add("#AVAILABLE", dd_available.SelectedItem.ToString());
cmd.Parameters.Add("#CATEGORY", dd_category.SelectedValue);
cmd.Parameters.Add("#BRAND", dd_brand.SelectedValue);
cmd.Parameters.Add("#ACHIV", dd_achievment.SelectedValue);
param.InsertUpdateData(cmd);
}
}
It is getpicture function used in btn_submit
private void getpicture()
{
try
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string root = Server.MapPath("~");
string path = root + "assets\\images\\products\\";
FileUpload1.SaveAs(path + FileName);
ViewState["pathimage"] = "/assets/images/products/" + FileName;
this.product_image.ImageUrl = "../assets/images/products/upload.png";
}
else
{
Response.Write("Select an Image");
}
}
catch (Exception ex)
{
Response.Write("Select an Image");
}
}
Providing Data access layer Insert Update Data code too
public Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["OnlineStoreConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
System.Web.HttpContext.Current.Response.Write("Succed");
return true;
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.ToString());
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Server Controls
<div class="row">
<div class="col-md-6">
<asp:TextBox ID="txt_name" runat="server" CssClass="form-control" placeholder="Product Name"></asp:TextBox>
<br />
<asp:TextBox ID="txt_price" runat="server" CssClass="form-control" placeholder="Product Price"></asp:TextBox>
<br />
<asp:TextBox ID="txt_unit" runat="server" CssClass="form-control" placeholder="Product Unit"></asp:TextBox>
<br />
<asp:DropDownList ID="dd_available" runat="server" CssClass="form-control">
<asp:ListItem>Is Product Available</asp:ListItem>
<asp:ListItem>Available</asp:ListItem>
<asp:ListItem>Not Avaliable</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="dd_category" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_brand" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
<asp:DropDownList ID="dd_achievment" runat="server" CssClass="form-control"></asp:DropDownList>
<br />
</div>
<div class="col-md-2"></div>
<div class="col-md-4">
<asp:Image ID="product_image" runat="server" style="height:231px;width:225px;" CssClass="form-control" />
<asp:FileUpload ID="FileUpload1" runat="server" onchange = "show_image(this);" />
</div>
</div>
<br />
<div class="row">
<div class="col-md-3 col-md-offset-6">
<asp:Button ID="btn_Insert" runat="server" Text="Create Product" CssClass="btn btn-primary btn-lg" OnClick="btn_Insert_Click" />
</div>
</div>
Before Clicking update button
Before clicking update button
After I updated text box values respectively and when click button Upload None of my server control value changes. Here it is
Watching local variable
But in case of Creating Product it works
Saad, i think the error is in the page_load event. If in your querystring the update param is not null, then you are always replacing the textboxes with the data of your DB.
Your code should be like this
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["update"] !=null)
{
if (!Page.IsPostBack)
{
bindcategories();
bindachievments();
bindbrands();
int id = int.Parse(Request.QueryString["update"]);
string query = "SELECT * FROM ProductView WHERE id = " + id.ToString();
DataTable dtupd = new DataTable();
dtupd = param.All_data(query);
string name = "",available="",category="",brand="",achievement="",image="";
decimal price=0;
int unit = 0;
foreach (DataRow row in dtupd.Rows)
{
name = row.Field<string>("product_name");
price = row.Field<decimal>("price");
unit = row.Field<int>("unit");
image = row.Field<string>("product_image");
available = row.Field<string>("available");
category = row.Field<string>("category_name");
brand = row.Field<string>("brand_name");
achievement = row.Field<string>("achievement");
}
txt_name.Text = name;
txt_price.Text = price.ToString();
txt_unit.Text = unit.ToString();
product_image.ImageUrl = "../" + image;
dd_available.ClearSelection();
dd_available.SelectedValue = available;
dd_category.ClearSelection();
dd_category.Items.FindByText(category).Selected = true;
dd_brand.ClearSelection();
dd_brand.Items.FindByText(brand).Selected = true;
dd_achievment.ClearSelection();
dd_achievment.Items.FindByText(achievement).Selected = true;
btn_Insert.Text = "Update Product";
}
}
else
{
if (!Page.IsPostBack)
{
bindcategories();
bindbrands();
bindachievments();
}
if (!FileUpload1.HasFile)
{
product_image.ImageUrl = "../assets/images/products/default.png";
}
}
}
Hope it helps...

Dropdownlist not showing correct selected value in ASP.NET Repeater Web application

I have a few ASP.NET Repeaters that have drop down lists in them and they all need to be populated with the correct information and then display the selected value for each data row it is displaying. In one repeater (CompanyRepeater), the correct selected value is chosen. In another repeater (SoldRepeater), the correct selected value is NOT chosen. So the drop down list in CompanyRepeater does work but the one in SoldRepeater does not work. The code is the same for both repeaters and I cannot figure out why the second one is not working. Both drop down lists populate with the correct information but the second repeater does not display the correct selected value. Please help me figure out why the correct selected value is not being selected. Below is my code. Please let me know if there is anymore information needed to help me. Any help is much appreciated. First is my front end code.
<asp:Repeater ID="CompanyRepeater" runat="server" OnItemDataBound="CompanyRepeater_ItemDataBound" OnItemCommand="CompanyRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Company</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtDate" runat="server" Text='<%#Eval("Date") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>OldName
<br />
<asp:TextBox ID="txtOldNameChange" Text='<%#Eval("OldName") %>' runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:
<asp:DropDownList ID="ddlCountry" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
<br /> State:
<asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>
</td>
<td>New Name
<br />
<asp:TextBox ID="txtNewNameChange" runat="server" Text='<%#Eval("NewName") %>'></asp:TextBox>
</td>
<td rowspan="3" style="width: 50px; float: right;">
<asp:Button ID="btnUpdateName" runat="server" Text="Update" CommandName="Update" />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
<hr />
<asp:Repeater ID="SoldRepeater" runat="server" OnItemDataBound="SoldRepeater_ItemDataBound" OnItemCommand="SoldRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Sold Event</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtSoldDate" runat="server" Text='<%#Eval("EventDate") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtSoldNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>Sold to Company
<br />
<asp:TextBox ID="txtSoldTo" Text='<%#Eval("SoldToCompany") %>' runat="server"></asp:TextBox>
<br /> Sold to Type
<asp:DropDownList ID="ddlSoldTo" runat="server"></asp:DropDownList>
</td>
<td rowspan="2">
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%#Eval("CompID") %>' />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
This is my backend code
protected void Page_Load(object sender, EventArgs e)
{
_cID = Convert.ToInt32(Request.QueryString["CompID"]);
if (!Page.IsPostBack)
{
PopulateCompanyRepeater();
PopulateSoldEvent();
}
}
private void PopulateCompanyRepeater()
{
DALAccessData a = new DALAccessData(connString);
_listInfo = a.GetCompInfo(_cID);
CompanyRepeater.DataSource = _listInfo;
CompanyRepeater.DataBind();
}
private void PopulateSoldEvent()
{
DALSectionAccessData a = new DALSectionAccessData(connString);
_listEvents = a.GetSoldEvents(_cID);
SoldRepeater.DataSource = _listEvents;
SoldRepeater.DataBind();
}
protected void CompanyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)e.Item.FindControl("ddlState");
Corp co = (Corp)e.Item.DataItem;
Corp st = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT a.Country_ID, a.CountryName FROM States c INNER JOIN Countries a ON a.Country_ID = c.Country_ID";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "CountryName";
ddl.DataValueField = "Country_ID";
ddl.DataBind();
cn.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (co.Country_ID == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
}
else
{
ddl.Items[i].Selected = false;
}
}
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl2.DataSource = ds.Tables[0];
ddl2.DataTextField = "StateName";
ddl2.DataValueField = "StateID";
ddl2.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl2.Items.Count; i++)
{
if (!String.IsNullOrEmpty(ddl2.Items[i].Value))
{
if (st.StateID == Convert.ToInt32(ddl2.Items[i].Value))
{
ddl2.Items[i].Selected = true;
}
else
{
ddl2.Items[i].Selected = false;
}
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlState");
ddl2.Items.Clear();
using(SqlConnection conn = new SqlConnection(connString))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cmd.Connection = conn;
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem _listStates = new ListItem();
_listStates.Text = sdr["StateName"].ToString();
_listStates.Value = sdr["StateID"].ToString();
ddl2.Items.Add(_listStates);
}
}
}
}
ddl2.AppendDataBoundItems = true;
ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
ddl2.SelectedIndex = -1;
}
protected void SoldRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlSoldTo");
int x = ((CorpEvents)e.Item.DataItem).SoldToTypeID;
//Corp x = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT SoldToTypeID, SoldToTypeName FROM SoldToType";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "SoldToTypeName";
ddl.DataValueField = "SoldToTypeID";
ddl.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
}
}
My data access layer code
public List <Corp> GetCompInfo(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, CONVERT(varchar(10), a.Date, 120) AS Date, a.Notes, b.StateID, b.OldName, b.NewName, c.Country_ID FROM NameChange b INNER JOIN CompanyInfo a ON a.CompID = b.CompID INNER JOIN States c ON c.StateID = b.StateID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.NewName = row["NewName"].ToString();
e.OldName = row["OldName"].ToString();
e.StateID = Convert.ToInt32(row["StateID"].ToString());
e.Notes = row["Notes"].ToString();
e.CountryID = Convert.ToInt32(row["Country_ID"].ToString());
e.Date = Convert.ToDateTime(row["Date"].ToString());
e.Date.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
public List <Corp> GetSoldEvents(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, a.Notes, a.Date, b.SoldToCompany, c.SoldToTypeName, c.SoldToTypeID FROM CompanyInfo a INNER JOIN SoldEvent b ON a.CompID = b.CompID INNER JOIN SoldToType c ON b.SoldToTypeID = c.SoldToTypeID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.SoldToCompany = row["SoldToCompany"].ToString();
e.SoldToTypeName = row["SoldToTypeName"].ToString();
e.SoldToTypeID = Convert.ToInt32(row["SoldToTypeID"].ToString());
e.Notes = row["Notes"].ToString();
e.EventDate = Convert.ToDateTime(row["Date"].ToString());
e.EventDate.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
IMHO, your method of setting the selected value is rather cumbersome. This entire section of code:
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
Can be replaced with a single line:
ddl.SelectedValue = x.ToString();
In addition, once you do find the matching value you continue to loop on the items, rather than exiting out of the loop.
Try these changes, they may solve the problem for you.
A few other items that I noticed:
The code to retrieve the SoldToType is called for each item in the
repeater. I would suggest retrieving this data once and referencing
it for each item, rather than going to the db each time.
Your SQL code is wide open to SQL injection. Use parameterized queries, like so:
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = #CountryID";
...
cmd.Parameters.AddWithValue("CountryID", ddl.SelectedValue);

Why asp:DropDownList does not respond to code-behind

I have the following ASP drop-down:
<asp:DropDownList ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
<asp:ListItem Text="BY LOCATION" Value="1" />
<asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>
<br /><br />
<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
I am trying to make it interactive where if the first select option is changed the second will change as well based on the selection from the first select option.
My C# code looks like this:
public partial class test : System.Web.UI.Page
{
String cString;
SqlConnection Conn;
protected void Page_Load(object sender, EventArgs e) {
PopulatePhysician();
//PopulateSpecialty();
//PopulateLocation();
}
public void PopulatePhysician() {
SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
//cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Physician's Name";
Item.Value = "0";
//Item.Selected = True
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateSpecialty() {
SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Specialty";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
//}
cmd.Connection.Close();
cmd.Connection.Dispose();
}
public void PopulateLocation() {
SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues = default(SqlDataReader);
ddlValues = cmd.ExecuteReader();
//if (!IsPostBack) {
ddlDrillDown.DataSource = ddlValues;
ddlDrillDown.DataValueField = "content_id";
ddlDrillDown.DataTextField = "content_title";
ddlDrillDown.DataBind();
//set the default value for the drop down
ListItem Item = new ListItem();
Item.Text = "Select a Location";
Item.Value = "0";
ddlDrillDown.Items.Insert(0, Item);
cmd.Connection.Close();
cmd.Connection.Dispose();
//}
}
public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
switch(ddlMain.SelectedItem.Value) {
case "0":
PopulatePhysician();
break;
case "1":
PopulateLocation();
break;
case "2":
PopulateSpecialty();
break;
}
}
}
When the page first loads, PopulatePhysician(); works great by populating the select option. But when I call the SelectedIndexChanged() function, nothing happens.
How can I resolve it? Is the case statement correct?
You haven't added any delegates to the SelectedIndexChanged event.
Add OnSelectedIndexChanged to the parameters in the asp:DropDownList tag, like so:
<asp:DropDownList ClientIDMode="Static" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true" >
EDIT
I just noticed you're actually missing the AutoPostBack event as well - it should be set to true, as updating the selection without submitting the form will not fire a postback event, unless AutoPostBack is set to true.
It needs AutoPostback=true on the Dropdown list
<asp:DropDownList AutoPostback="true" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
Remove the If (!IsPostBack) clause from your functions. Check for that in page load, but not in each individual function.

Change gridview header text when i choose dropdownlist

I have some doubt
This is my coding for aspx page and .cs page
How can I achieve the following
If i select February the header text assigned January value and i select march then assign February value...Could you please help me find a solution for it
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:TemplateField HeaderText="8-14">
<ItemTemplate>
<asp:TextBox ID="TxtWeek2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In .CS page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add("Select");
DropDownList1.Items.Add("January");
DropDownList1.Items.Add("February");
DropDownList1.Items.Add("March");
DropDownList1.Items.Add("April");
DropDownList1.Items.Add("May");
SqlConnection cn = new SqlConnection("Data Source=192.169.10.22;Initial Catalog=SHRICITYUNO;User ID=uno;Password=uno");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd = new SqlCommand("SELECT Week1 FROM Finman_FundPlan", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedItem.Text.ToString();
if (DropDownList1.SelectedItem.Text == "January")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "February")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "-";
}
else if (DropDownList1.SelectedItem.Text == "March")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "April")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-30";
}
else if (DropDownList1.SelectedItem.Text == "May")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
}
you can do it using Javascript at client side.
if you observe the grid view then you can notice that row[0] is the header row for gridview.
now you can check decide the which cell test you have to change.
see the following javascript function to accomplish your task
<script language="Javascript">
function ChangeHeaderText()
{
var gridObject = document.getElementById("Gridview1");
gridObject.rows[0].cells[0].innerText = 'NewHeader Text';
return false;
}
</script>
//call above function on 'onchange' event of dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange = "return ChangeHeaderText()"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Try this It will work......

Categories