I am retrieving data from table Technology in dropdownlist ddlTechnology .
I have TechnologyId as primary key in the table and values are 1,2,3,4
Now as per the technology,i have to add questions in question bank. but when i select any item in dropdownlist, my SelectedIndex is always 0.
i want TechnologyId from dropdownlist.
i have tried following code but its not working
using (dbDataContext dt = new dbDataContext())
{
var qry = from i in dt.Technologies
select i;
ddlTechnology.DataSource = qry;
ddlTechnology.DataValueField = "TechnologyId";
ddlTechnology.DataTextField = "TechnologyName";
ddlTechnology.DataBind();
ddlTechnology.Items.Insert(0, new ListItem("Select Technology", ""));
}
Add button to add question according to selected technology.
protected void btnAdd_Click(object sender, EventArgs e)
{
using (dbDataContext dt = new dbDataContext())
{
Question objQtn = new Question();
objQtn.Question1 = txtQuestion.Text;
objQtn.Option1 = txtOption1.Text;
objQtn.Option2 = txtOption2.Text;
objQtn.Option3 = txtOption3.Text;
objQtn.Answer = txtAnswer.Text;
// below here selectedIndex is always zero..
objQtn.TechnologyId = ddlTechnology.SelectedIndex;
dt.Questions.InsertOnSubmit(objQtn);
dt.SubmitChanges();
txtAnswer.Text = "";
txtOption1.Text = "";
txtOption2.Text = "";
txtOption3.Text = "";
txtQuestion.Text = "";
}
}
Reason1:
Seems like you are binding dropdownlist on every postback. If that is a problem then keeping your load code in !IsPostBack shou work.
if(!IsPostBack)
{
using (dbDataContext dt = new dbDataContext())
{
var qry = from i in dt.Technologies
select i;
ddlTechnology.DataSource = qry;
ddlTechnology.DataValueField = "TechnologyId";
ddlTechnology.DataTextField = "TechnologyName";
ddlTechnology.DataBind();
ddlTechnology.Items.Insert(0, new ListItem("Select Technology", ""));
}
}
Reason 2:
In some cases if programmer disables ViewState property of any control/page then also control looses it's value on postback.
Need to bind dropdown list in the below event.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Bind your dropdown list
}
}
Please find the code for ref. hope it will help you:
(objQtn.TechnologyId = ddlTechnology.SelectedIndex;)
one of these two is of string type check once.
Index.aspx
<asp:DropDownList ID="ddlCloth" runat="server"></asp:DropDownList>
<asp:Button runat="server" ID="btnSave" OnClick="btnSave_Click" />
Index.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt1 = new DataTable();
dt1.Columns.AddRange(new DataColumn[2] { new DataColumn("Id"), new DataColumn("Name") });
dt1.Rows.Add(1, "Shirt");
dt1.Rows.Add(2, "Jeans");
ddlCloth.DataSource = dt1;
ddlCloth.DataTextField = "Name";
ddlCloth.DataValueField = "Id";
ddlCloth.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(ddlCloth.SelectedItem.Value);
string text = Convert.ToString(ddlCloth.SelectedItem.Text);
int index=Convert.ToInt32(ddlCloth.SelectedIndex);
}
Related
There is a listbox with name lbx_Marked, having autopostback turned on and selectedIndexChanged Method. But no matter whatever I do the SelectedIndex value always gets STICK To -1.
How to obtain the real SelectedIndex Value?
Below is the code for selectedIndex Method.
protected void lbx_Marked_SelectedIndexChanged(object sender, EventArgs e)
{
string a;
int b;
b=lbx_Marked.SelectedIndex;
if (lbx_Marked.SelectedIndex == -1)
{
a = " No Selection Made";
}
}
The code for populating the listBox is as below.
private void FillControls()
{
using (SqlConnection con = new SqlConnection(cs))
{
int i;
List<string> mylist = new List<string>();
SqlDataAdapter da = new SqlDataAdapter("select Id,Empname,Designation from TblMstEmp", con);
DataSet ds = new DataSet();
da.Fill(ds, "entry");
for(i=0;i<ds.Tables["entry"].Rows.Count;i++)
{
mylist.Add(string.Concat( Convert.ToString( ds.Tables["entry"].Rows[i]["Empname"]),"-",Convert.ToString(ds.Tables["entry"].Rows[i]["Designation"]))) ;
}
lbx_Marked.DataSource =mylist;
lbx_Marked.DataBind();
}
}
I assume you are using WebForms. I just created a new C# WebForms project and added the following ListBox control and Code Behind
Default.aspx
<asp:ListBox runat="server" ID="lbx_Marked" AutoPostBack="True" OnSelectedIndexChanged="lbx_Marked_SelectedIndexChanged" />
Default.aspx.cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lbx_Marked.Items.Add(new ListItem("Option 1", "1"));
lbx_Marked.Items.Add(new ListItem("Option 2", "2"));
lbx_Marked.Items.Add(new ListItem("Option 3", "3"));
}
}
protected void lbx_Marked_SelectedIndexChanged(object sender, EventArgs e)
{
string a;
int b;
b = lbx_Marked.SelectedIndex;
if (lbx_Marked.SelectedIndex == -1)
{
a = " No Selection Made";
}
}
}
Clicking a different option in the ListBox resulted in a POST back and the SelectIndex always reflected the value of the ListItem
UPDATED
I added data in the same manner as you indicated and it still works for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> mylist = new List<string>();
mylist.Add("Option 1");
mylist.Add("Option 2");
mylist.Add("Option 3");
lbx_Marked.DataSource = mylist;
lbx_Marked.DataBind();
}
}
I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();
So,
I have a drop down list whish fill by a result of SQL query in my event page_Load. What i want to do it's get the current value when the event selectedIndexChanges on my drop down list is fired and put it in a textbox.
Look my code below.
My drop down list definition: <asp:DropDownList ID="ddProfil" runat="server" Width="550" AutoPostBack="True" OnSelectedIndexChanged="ddProfil_SelectedIndexChanged" >
My page load event: protected void Page_Load(object sender, EventArgs e)
{
loadDDProfil(Request.QueryString["sitename"]);
}
Function which load the drop down list:
protected void loadDDProfil(string siteName)
{
SqlCommand requete = new SqlCommand();
requete.Connection = connWeb.ConnectionToDb;
requete.CommandType = System.Data.CommandType.Text;
string strReq = "ps_get_all_IndexProfil " + "MRF";
requete.CommandText = strReq;
DataTable dtPrf = connWeb.ExecuteQueryDB(requete);
SqlDataAdapter adapter = new SqlDataAdapter(requete);
adapter.Fill(dtPrf);
var dtSource = from p in dtPrf.AsEnumerable()
select new {
ind = p.Field("IndexProfil"),
DisplayedField = String.Format("{0} [ {1} ]", p.Field("NomProfil"), p.Field("Description"))
};
ddProfil.DataSource = dtSource;
ddProfil.DataValueField = "ind";
ddProfil.DataTextField = "DisplayedField";
ddProfil.DataBind();
ddProfil.SelectedIndexChanged += ddProfil_SelectedIndexChanged;
And the event Selected Index Changed:
public void ddProfil_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddProfil.SelectedValue;
}
Thank you, for your help.
I believe your answer is here https://taditdash.wordpress.com/2014/05/21/why-dropdownlist-selectedvalue-not-working-inside-selectedindexchanged-event/
On your page load event try adding this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadDDProfil(Request.QueryString["sitename"]);
}
}
I have used below code to first retrieve category Id from category entity and bind it to the dropdownlist that is DropDownlistCategory .Now I want to insert that category ID from dropdownlist to product entity which contains four columns in the database such as
ProductName,CategoryID,QuantityPerUnit and UnitPrice.
But while inserting dropdownlist value it will always select the first value from dropdownlist.
Using this :
prod.CategoryID = Convert.ToInt32(DropDownListCategory.SelectedValue);
Is it correct?
NewProduct.aspx code:-
<asp:DropDownList ID="DropDownListCategory" runat="server"CssClass="form- control" Width="100px" OnSelectedIndexChanged="DropDownListCategory_SelectedIndexChanged" >
</asp:DropDownList>
NewProduct.cs code:-
LaunderDBEntities context = new LaunderDBEntities();
protected void Page_Load(object sender, EventArgs e)
{
var categoryId = from cat in context.Categories
select new
{
categoryID = cat.CategoryID,
};
DropDownListCategory.DataSource = categoryId.ToList();
DropDownListCategory.DataValueField = "categoryID";
DropDownListCategory.DataTextField = "categoryID";
DropDownListCategory.DataBind();
}
protected void btnAddProduct_Click(object sender, EventArgs e)
{
SaveProductInfo();
}
private void SaveProductInfo()
{
Product prod = new Product();
prod.ProductName = txtProductName.Text;
prod.CategoryID = Convert.ToInt32(DropDownListCategory.SelectedValue);
prod.QuantityPerUnit = Convert.ToInt32(txtQuantity.Text);
prod.UnitPrice =Convert.ToInt32(txtUnitPrice.Text);
ProductDA prdDa = new ProductDA();
prdDa.InertProductDetails(prod);
Label5.Text = "<p style='color:Green;'>Information Successfully saved!</p>";
Response.Redirect("ProductInfo.aspx");
}
Use IsPostBack in page load. Bind dropdown list only when page is load first time.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//.... code to bind the dropdownlist
}
}
I have a webpage that has a Telerik RadComboBox in radgrid control on the page,and i have a SqlserverCe database.My issue is how can i write the code to bind the RadCombobox at page load event in asp.net please help me.....
Items are bound to RadComboBox basically in the same way as to an ASP.NET DropDownList.
You can bind the RadComboBox to ASP.NET 2.0 datasources, ADO.NET DataSet/DataTable/DataView, to Arrays and ArrayLists, or to an IEnumerable of objects. And of course you can add the items one by one yourself. With RadComboBox, you'll use RadComboBoxItems instead of ListItems.
In one way or other, you'll have to tell the combobox what is each item's text and value.
Working with Items in Server Side Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadComboBoxItem item1 = new RadComboBoxItem();
item1.Text = "Item1";
item1.Value = "1";
RadComboBox1.Items.Add(item1);
RadComboBoxItem item2 = new RadComboBoxItem();
item2.Text = "Item2";
item2.Value = "2";
RadComboBox1.Items.Add(item2);
RadComboBoxItem item3 = new RadComboBoxItem();
item3.Text = "Item3";
item3.Value = "3";
RadComboBox1.Items.Add(item3);
}
}
Binding to DataTable, DataSet, or DataView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=LOCAL;Initial Catalog=Combo;Integrated Security=True");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Text], [Value] FROM [Links]", con);
DataTable links = new DataTable();
adapter.Fill(links);
combo.DataTextField = "Text";
combo.DataValueField = "Value";
combo.DataSource = links;
combo.DataBind();
}
}
EDIT: RadComboBox in a Grid:
Inside a RadGrid, it is perhaps easiest to use load on demand, by setting EnableLoadOnDemand="True" and handling the OnItemsRequested event.
protected void RadComboBox1_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
string sql = "SELECT [SupplierID], [CompanyName], [ContactName], [City] FROM [Suppliers] WHERE CompanyName LIKE #CompanyName + '%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql,
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
adapter.SelectCommand.Parameters.AddWithValue("#CompanyName", e.Text);
DataTable dt = new DataTable();
adapter.Fill(dt);
RadComboBox comboBox = (RadComboBox)sender;
// Clear the default Item that has been re-created from ViewState at this point.
comboBox.Items.Clear();
foreach (DataRow row in dt.Rows)
{
RadComboBoxItem item = new RadComboBoxItem();
item.Text = row["CompanyName"].ToString();
item.Value = row["SupplierID"].ToString();
item.Attributes.Add("ContactName", row["ContactName"].ToString());
comboBox.Items.Add(item);
item.DataBind();
}
}
You can also bind the combobox manually in the grid's OnItemDataBoundHandler event:
protected void OnItemDataBoundHandler(object sender, GridItemEventArgs e)
{
if (e.Item.IsInEditMode)
{
GridEditableItem item = (GridEditableItem)e.Item;
if (!(e.Item is IGridInsertItem))
{
RadComboBox combo = (RadComboBox)item.FindControl("RadComboBox1");
// create and add items here
RadComboBoxItem item = new RadComboBoxItem("text","value");
combo.Items.Add(item);
}
}
}