How to bind values in usercontrol dropdownlist? - c#

I bind the values in usercontrol dropdownlist
But when I add the usercontrol row that time values are not binded in dropdownlist
Code:
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TimesheetUserControl.ascx.cs" Inherits="Portal.TimesheetUserControl" %>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownActivities" Width="150px" runat="server"></asp:DropDownList>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</td>
</tr>
.aspx
<uc:Timesheet ID="Timesheet" runat="server" />
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
BindActivities();
}
}
protected void BindActivities()
{
DropDownList dropActivities = Timesheet.FindControl("DropDownActivities") as DropDownList;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (IsPostBack)
{
GenerateControls();
}
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
TimesheetUserControl ctrl = (TimesheetUserControl)Page.LoadControl("TimesheetUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
Button thisButton = (Button)sender;
List<string> temp = null;
var uc = (TimesheetUserControl)this.LoadControl(#"TimesheetUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
In the below image if Click add button rows are added but in second values are not binded in dropdownlist
Any ideas? Thanks in advance.

find the user controls by the id you given and then you can find the DropDownList inside the usercontrol.
protected void BindActivities()
{
foreach (string controlName in NoOfControls)
{
TimesheetUserControl userControl = Timesheet.FindControl(controlName) as TimesheetUserControl;
if(userControl == null) return;
DropDownList dropActivities = userControl.FindControl("DropDownActivities") as DropDownList;
if(dropActivities == null) return;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
}

Related

dropdown list in record update page not listing other records

I have a record update page which seems to populate all the fields, however the dropdown lists will only list the data from that particular record, it is not listing the other School Names and the Student Names. The two dropdown lists are cascaded i.e. selecting the School Name ddl should list only the Students that are from that school in the Student ddl.
Any help on this will be much appreciated, thank you.
Gridview code on tours.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging" OnEditCommand="EditAddress" PageSize="5">
<Columns>
<asp:HyperLinkField Text="Update" DataNavigateUrlFields="TourId" DataNavigateUrlFormatString="~/abcrud1/tours_update.aspx?TourId={0}" />
<asp:BoundField DataField="TourId" HeaderText="TourId" HtmlEncode="false" />
<asp:BoundField DataField="VisitorName" HeaderText="VisitorName" HtmlEncode="false" />
<asp:BoundField DataField="VisitorSchoolId" HeaderText="VisitorSchoolId" HtmlEncode="false" />
<asp:BoundField DataField="SchName" HeaderText="SchName" HtmlEncode="false" />
<asp:BoundField DataField="TourDate" HeaderText="TourDate" HtmlEncode="false" />
<asp:BoundField DataField="StudentId" HeaderText="StudentId" HtmlEncode="false" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" HtmlEncode="false" />
<asp:BoundField DataField="LastName" HeaderText="LastName" HtmlEncode="false" />
</Columns>
</asp:GridView>
tour_update.aspx
<form id="form1" runat="server">
<div>
<table style="width: 50%;">
<tr>
<td style="width: 50%;">Tour Id:</td>
<td style="width: 50%;">
<asp:TextBox ID="txttourid" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Visitor Name:</td>
<td style="width: 50%;">
<asp:TextBox ID="txtvisname" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Visitor School:</td>
<td style="width: 50%;">
<asp:DropDownList ID="ddlvisschool" runat="server" AutoPostBack="true"></asp:DropDownList></td>
</tr>
<tr>
<td style="width: 50%;">Tour Date:</td>
<td style="width: 50%;">
<asp:TextBox ID="txttourdate" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 50%;">Student:</td>
<td style="width: 50%;">
<asp:DropDownList ID="ddlstudent" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td><asp:Button ID="btnUpdate" Text="Update" runat="server" OnClick="TourUpdate_click" /></td>
<td></td>
</tr>
</table>
</div>
</form>
tour_update.aspx.cs
{
public partial class tours_update : System.Web.UI.Page
{
string constr = ConfigurationManager.ConnectionStrings["SQLConnectionString2"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
{
if (!IsPostBack)
{
this.GetTour();
}
}
}
protected void TourUpdate_click(object sender, EventArgs e)
{
this.TourUpdate();
}
private int id
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["TourId"]) ? int.Parse(Request.QueryString["TourId"]) : 0;
}
}
private void TourUpdate()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE tblCRUD1_Tour SET VisitorName=#VisitorName, VisitorSchoolId=#VisitorSchoolId, TourDate=#TourDate, StudentId=#StudentId WHERE TourId=#TourId", con))
{
cmd.Parameters.AddWithValue("#TourId", id);
cmd.Parameters.AddWithValue("#VisitorName", txtvisname.Text);
cmd.Parameters.AddWithValue("#VisitorSchoolId", ddlvisschool.SelectedItem.Value);
cmd.Parameters.AddWithValue("#TourDate", txttourdate.Text);
cmd.Parameters.AddWithValue("#StudentId", ddlstudent.SelectedItem.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/abcrud1/tours.aspx");
}
}
}
private void GetTour()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(#"SELECT tblCRUD1_Tour.TourId, tblCRUD1_Tour.VisitorName, tblCRUD1_Tour.VisitorSchoolId, tblCRUD1_School.SchName, tblCRUD1_Tour.TourDate, tblCRUD1_Tour.StudentId, tblCRUD1_Student.FirstName, tblCRUD1_Student.LastName
FROM tblCRUD1_Tour
INNER JOIN tblCRUD1_Student ON tblCRUD1_Tour.StudentId = tblCRUD1_Student.StudentId
INNER JOIN tblCRUD1_School ON tblCRUD1_Student.LastSchoolId = tblCRUD1_School.SchId
WHERE tblCRUD1_Tour.TourId=#TourId", con))
{
cmd.Parameters.AddWithValue("#TourId", id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
this.txttourid.Text = dr["TourId"].ToString();
this.txtvisname.Text = dr["VisitorName"].ToString();
this.txttourdate.Text = dr["TourDate"].ToString();
ddlvisschool.DataSource = dt;
ddlvisschool.DataTextField = "SchName";
ddlvisschool.DataValueField = "VisitorSchoolId";
ddlvisschool.DataBind();
ddlstudent.DataSource = dt;
ddlstudent.DataTextField = "LastName";
ddlstudent.DataValueField = "StudentId";
ddlstudent.DataBind();
}
}
}
}
}
}
}
tours_add.aspx.cs
{
public partial class tours_add : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString2"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bindddlvisschool();
ddlstudent.Items.Insert(0, " Select Pupil ");
}
}
private void Bindddlvisschool()
{
con.Open();
string str = #"Select * FROM tblCRUD1_School ORDER BY SchName ASC";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlvisschool.DataSource = dt;
ddlvisschool.DataTextField = "SchName";
ddlvisschool.DataValueField = "SchId";
ddlvisschool.DataBind();
ddlvisschool.Items.Insert(0, new ListItem(" Choose Last School ", "0"));
ddlvisschool.SelectedIndex = 0;
con.Close();
}
protected void TourAdd_click(object sender, EventArgs e)
{
con.Open();
string str = #"INSERT INTO tblCRUD1_Tour (VisitorName,VisitorSchoolId,TourDate,StudentId) VALUES (#VisitorName,#VisitorSchoolId,#TourDate,#StudentId)";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("#VisitorName", txtvisname.Text);
cmd.Parameters.AddWithValue("#VisitorSchoolId", ddlvisschool.Text);
cmd.Parameters.AddWithValue("#TourDate", txttourdate.Text);
cmd.Parameters.AddWithValue("#StudentId", ddlstudent.Text);
cmd.ExecuteNonQuery();
lblmessage1.Text = "Tour added successfully";
con.Close();
Response.AddHeader("REFRESH", "3;URL=tours.aspx");
}
protected void ddlvisschool_SelectedIndexChanged(object sender, EventArgs e)
{
string get_SchId;
string get_SchName;
get_SchId = ddlvisschool.SelectedValue.ToString();
get_SchName = ddlvisschool.SelectedItem.Text;
if (get_SchId != "0")
{
con.Open();
SqlDataAdapter da;
DataSet ds = new DataSet();
string query;
query = "SELECT tblCRUD1_Tour.TourId, tblCRUD1_Tour.VisitorName, tblCRUD1_Tour.VisitorSchoolId, tblCRUD1_School.SchName, tblCRUD1_Tour.TourDate, tblCRUD1_Tour.StudentId, tblCRUD1_Student.FirstName, tblCRUD1_Student.LastName "
+ "FROM tblCRUD1_Tour "
+ "INNER JOIN tblCRUD1_Student ON tblCRUD1_Tour.StudentId = tblCRUD1_Student.StudentId "
+ "INNER JOIN tblCRUD1_School ON tblCRUD1_Student.LastSchoolId = tblCRUD1_School.SchId "
+ "WHERE tblCRUD1_Tour.VisitorSchoolId='" + get_SchId.ToString() + "' ORDER BY tblCRUD1_Student.LastName ASC";
da = new SqlDataAdapter(query, con);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
ddlstudent.DataSource = ds;
ddlstudent.DataTextField = "LastName";
ddlstudent.DataValueField = "StudentId";
ddlstudent.DataBind();
//ddlstudent.Items.Insert(0, new ListItem(get_SchName.ToString(), "0"));
ddlstudent.SelectedIndex = 0;
}
else
{
ddlstudent.Items.Insert(0, "No Student");
ddlstudent.DataBind();
}
}
}
}
}

How to display questions and options(as a radiobuttonlist) in datalist

I am developing an application (Quiz Engine) in Asp.Net with C#. I have a database table (Q_ID,Question,option1,option2,option3,answer).
What I want is, to retrieve these data and display to the user as Question and Answer and enable the user to select with the Radio button. My problem is that how I can display this Question and options in radiobuttonlist.
my asp page is
<asp:DataList ID="DataList2" runat="server" RepeatDirection="Vertical">
<ItemTemplate>
<br />
<table class="auto-style1">
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Question") %>'></asp:Label>
</td>
<td>
<asp:RadioButtonList ID="RadioButtonList2" runat="server">
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and my cod behind is like
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
DataTable dt = new DataTable();
string connStr = #"Data Source=localhost;Database=ahsschema;User Id=webuser;Password=webuser2014";
using (MySqlConnection cn = new MySqlConnection(connStr))
{
MySqlDataAdapter adp = new MySqlDataAdapter("select LO_id,Q_Id,level,Question,option1,option2 from quiz WHERE LO_id='LO111'", cn);
adp.Fill(dt);
}
if (dt.Rows.Count > 0)
{
DataList2.DataSource = dt;
DataList2.DataBind();
}
foreach (DataListItem dli in DataList2.Items)
{
RadioButtonList RadioButtonList2 = (RadioButtonList)DataList2.FindControl("RadioButtonList2");
//RadioButtonList2.Items.Clear();
RadioButtonList2.Items.Insert(0, new ListItem("option1".ToString(), "option1".ToString()));
RadioButtonList2.Items.Insert(1, new ListItem("option2".ToString(), "option2".ToString()));
}
}

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);

Same data comes twice in dropdown

I have 3 dropdown lists:
<tr>
<td align="left" class="style2">
Emp Code</td>
<td align="left">
<asp:UpdatePanel ID="UpdatePanel6" runat="server">
<ContentTemplate>
<div class="input-prepend" title="Select Machine ID" data-rel="tooltip">
<asp:DropDownList ID="ddcode" runat="server" AutoPostBack="True"
onselectedindexchanged="ddcode_SelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="ddcode" ForeColor="Red">*
</asp:RequiredFieldValidator>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td align="left" class="style2">
Company</td>
<td align="left">
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<div class="input-prepend" title="Select Machine ID" data-rel="tooltip">
<asp:DropDownList ID="ddcompany" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="ddcompany" ForeColor="Red">*
</asp:RequiredFieldValidator>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td align="left" class="style2">
Branch</td>
<td align="left">
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<div class="input-prepend" title="Select Machine ID" data-rel="tooltip">
<asp:DropDownList ID="ddbranch" runat="server"
onselectedindexchanged="ddbranch_SelectedIndexChanged">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="ddbranch" ForeColor="Red">*
</asp:RequiredFieldValidator>
</ContentTemplate> </asp:UpdatePanel>
</td>
</tr>
I also have a dropdown class:
public class Dropdown
{
Connection con = new Connection();
public void dropdwnlist(string qry, DropDownList ddl)
{
con.gettable(qry);
if (con.dt.Rows.Count > 0)
{
if (con.dt.Columns.Count == 2)
{
string str1 = con.dt.Columns[0].ColumnName.ToString();
string str2 = con.dt.Columns[1].ColumnName.ToString();
ddl.DataValueField = str1;
ddl.DataTextField = str2;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str1);
con.dt.Columns.Remove(str2);
}
else
{
string str = con.dt.Columns[0].ColumnName.ToString();
ddl.DataValueField = str;
ddl.DataTextField = str;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str);
//con.dt.Columns.Remove(str2);
}
}
ddl.Items.Insert(0, ("--Select--"));
}
My button click is:
Dropdown dwn = new Dropdown();
string str = "";
SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillempcode();
//fillcompany();
//filldepartment();
}
}
protected void fillempcode()
{
string str = "select MachID,EmpCode from EmpDetails where StatusID='0'";
dwn.dropdwnlist(str, ddcode);
}
protected void fillcompany()
{
//Where EmpCode='" + ddcode.SelectedItem.Text + "'
str = "select CompanyID,CompanyName from Company ";
dwn.dropdwnlist(str, ddcompany);
str = "select CompanyID from View_Company where EmpCode='" + ddcode.SelectedItem.Text + "'";
dr=conn.query(str);
if (dr.Read())
{
string id = dr[0].ToString();
ddcompany.SelectedItem.Text = id;
}
}
protected void fillbranch()
{
//where EmpCode='" + ddcode.SelectedItem.Text + "'
string str = "select BranchID,BranchName from View_Branch";
dwn.dropdwnlist(str, ddbranch);
}
My problem is I want to enable all dropdownllist when I selected on EmpCode dropdown list. now it works fine but Company and Branch dropdown shows same value twise. may I know the reason?
Try rewriting the dropdwnlist method like this,
public void dropdwnlist(string qry, DropDownList ddl)
{
ddl.Items.Clear();
con.gettable(qry);
if (con.dt.Rows.Count > 0)
{
if (con.dt.Columns.Count == 2)
{
string str1 = con.dt.Columns[0].ColumnName.ToString();
string str2 = con.dt.Columns[1].ColumnName.ToString();
ddl.DataValueField = str1;
ddl.DataTextField = str2;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str1);
con.dt.Columns.Remove(str2);
}
else
{
string str = con.dt.Columns[0].ColumnName.ToString();
ddl.DataValueField = str;
ddl.DataTextField = str;
ddl.DataSource = con.dt;
ddl.DataBind();
con.dt.Columns.Remove(str);
//con.dt.Columns.Remove(str2);
}
}
ddl.Items.Insert(0, ("--Select--"));
ddl.SelectedIndex = 0;
}
Hope this helps...

Cannot refresh Listview after ItemCommand event is fired

I've a listview that allows Editing and Delete.
When I Click on the linkbutton in the listview, it fires up page_load then to OnItemCommand.
At the end of the command I added DataBind Which does not refresh my listview but deleted my entry.
If I change the DataBind to Redirect back to the same page with (...aspx?ID=...) it will return me a fresh new page. but in debug mode, I saw it run through page_load and the Databind.
<asp:UpdatePanel ID="UpdateOptions" runat="server" >
<ContentTemplate>
<asp:Panel ID="OPanel" runat="server" width="350px">
<asp:ListView runat="server" ID="lvPollOptions" DataKeyNames="POptionID" OnItemCommand="lvPollOptions_ItemCommand" OnDataBound="lvPollOptions_ItemDataBound" >
<LayoutTemplate>
<table cellpadding="0" cellspacing="0" border="0" width="300px">
<tr class="AdminListHeader">
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<%#Eval("OptionText")%>
</td>
<td>
<%#Eval("Votes")%>
</td>
<td align="center">
<asp:ImageButton runat="server" ID="ibtnEditOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Edit" ImageUrl="~/images/buttons/EditPencil.gif" AlternateText="Edit" CssClass="AdminImg" />
</td>
<td>
<asp:ImageButton runat="server" ID="ibtnDeleteOption" CommandArgument='<%# Eval("POptionID").ToString() %>' CommandName="Delete" ImageUrl="~/images/buttons/delete.gif" AlternateText="Delete" CssClass="AdminImg" OnClientClick="return confirm('Warning: This will delete the Poll Option from the database.');" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Label ID="lblNoOption" runat="server" Text="No Options Added"></asp:Label>
<table width="345px">
<tr>
<td width="100px">
Option:
</td>
<td>
<asp:TextBox ID="txtOption" runat="server" width="200px"></asp:TextBox>
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
string PID = Request.QueryString["ID"];
if (!IsPostBack)
{
if (PID == null)
{
}
else if (PID != null)
{
PollBindData();
}
}
}
protected void lvPollOptions_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string PID = Request.QueryString["ID"];
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataSet dsSel = new DataSet();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
}
protected void lvPollOptions_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string selectedID = e.CommandArgument.ToString();
SqlConnection connDeleteOption = new SqlConnection(connStr);
connDeleteOption.Open();
SqlCommand cmdDeleteOption = new SqlCommand("DELETE FROM [PollOptions] WHERE POptionID = '" + selectedID + "'", connDeleteOption);
cmdDeleteOption.ExecuteNonQuery();
connDeleteOption.Close();
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + selectedID);
}
if (e.CommandName == "Edit")
{
string EditID = e.CommandArgument.ToString();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmdView = new SqlCommand("SELECT OptionText From [PollOptions] Where POptionID = '" + EditID + "'", conn);
SqlDataReader dr1 = cmdView.ExecuteReader();
if (dr1.Read())
{
txtOption.Text = dr1["OptionText"].ToString();
}
Session["OptionID"] = txtOption.Text;
dr1.Close();
conn.Close();
lbOInsert.Visible = false;
lbOUpdate.Visible = true;
PollBindData();
//Response.Redirect("aAddEditPoll.aspx?ID=" + EditID);
}
}
Before we start - your code has a security risk since it is prone to Sql Injection, make sure you Parametrize your queries...
Now, your question is not very clear, but if I understand correctly, you're saying that after you delete an object, the Listview isn't refreshed after postback (e.g. you still see the deleted item). Since you're running in an UpdatePanel, make sure to update the panel after the DataBind...
Update PoolBindData like this
protected void PollBindData()
{
SqlConnection connOption = new SqlConnection(connStr);
connOption.Open();
// POTENTIAL SECURITY RISK - MAKE SURE YOU PARAMETRIZE THE QUERY!!
SqlDataAdapter da = new SqlDataAdapter("SELECT POptionID, OptionText, Votes FROM [PollOptions] Where PollID = '" + PID + "'", connOption);
DataTable dsSel = new DataTable();
da.Fill(dsSel);
lvPollOptions.DataSource = dsSel;
lvPollOptions.DataBind();
connOption.Close();
// Update panel
UpdateOptions.Update();
}

Categories