I want to bind dropdownlist to List<MyIem>,
in code behind.
<asp:DropDownList ID="listCategories" runat="server" Height="20px" CssClass="CategoryDropList" SelectedValue='<%# Bind("ParentId") %>' AutoPostBack="false" Width="300px">
Without using ObjectDataSource !
How can I Bind it to the dropdown list? In what event?
Also SelectedValue='<%# Bind("ParentId") %>' should work! (I mean the dropdownlist binding should occur before this!)
Made an example which will set the dropdown in the DataBound event.
Here is the markup
The way to use the ddl, is to find it with findcontrol() during DataBound event.
When you have the control in the DataBound event, you can also bind the dropdown to your List<>
Hope this helps.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:FormView ID="FormView1" runat="server" ondatabound="FormView1_DataBound">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
<asp:ListItem>Three</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:FormView>
</form>
</body>
</html>
Here is the code behind:
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> list = new List<string>();
list.Add("Some");
list.Add("Other");
FormView1.DataSource = list; //just to get the formview going
FormView1.DataBind();
}
protected void FormView1_DataBound(object sender, EventArgs e)
{
DropDownList ddl = null;
if(FormView1.Row != null)
ddl = (DropDownList) FormView1.Row.FindControl("DropDownList1");
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("Two"));
}
}
}
You can populate the DropDownList with another DataSource, assuming the valid values are in the database. Check out this video:
http://msdn.microsoft.com/en-us/data/cc546554.aspx
It's using an EntityDataSource instead of an ObjectDataSource, but the principle should still work.
If you want a "(none)" type option for null, see section "Converting Null in Template Fields" on this page:
http://msdn.microsoft.com/en-us/library/ms366709.aspx
Specifically:
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2"
DataTextField="Name" DataValueField="EmployeeID"
SelectedValue='<%# Bind("ReportsTo") %>' AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value="">(none)</asp:ListItem>
</asp:DropDownList>
Notice the the "AppendDataBoundItems" attribute and the "asp:ListItem" element.
well i was facing a similar problem. i noticed that you were trying to add it to and not which can be a major cause that you did not see it.
i have however worked on both the solutions provided above and found this worked for me :-
<EditItemTemplate>
<asp:DropDownList ID="ddlStream" runat="server" SelectedValue='<%# Bind("Stream") %>'>
<asp:ListItem>Common</asp:ListItem>
<asp:ListItem>Mechanical</asp:ListItem>
<asp:ListItem>Electronics</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" id="something" text='<%# Eval("Stream")%>'/>
</ItemTemplate>
hope this helpes you.
Related
I have a Submit button and on submit button click I want to check if my dropdown's selected index has changed or not. If yes, it should call a function.
I don't know how to do it in asp.net C#, need help.
<asp:DropDownList ID="ddlIncidentStatus" runat="server"
Enabled="false"
Display="Dynamic"
AppendDataBoundItems="True"
AutoPostBack="true"
CssClass="form-control">
<asp:ListItem Value="0">- Select Incident Status -</asp:ListItem>
</asp:DropDownList>
protected void btnSave_Click(object sender, System.EventArgs e)
{
if ((SaveToMemory() > 0))
{
//here i want to check if ddlIncidentStatus has change the value or not
Response.Redirect(("IncidentReport_New.aspx?OHSIncidentID=" +
Encryption.EncryptParameter(_incident.OHSIncidentID.ToString())));
}
}
}
Example.aspx
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DropDownListExample._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>Select a City of Your Choice</p>
<div>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value="">Please Select</asp:ListItem>
<asp:ListItem>New Delhi </asp:ListItem>
<asp:ListItem>Greater Noida</asp:ListItem>
<asp:ListItem>NewYork</asp:ListItem>
<asp:ListItem>Paris</asp:ListItem>
<asp:ListItem>London</asp:ListItem>
</asp:DropDownList>
</div>
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<br />
<asp:Label ID="Label1" runat="server" EnableViewState="False"></asp:Label>
</form>
</body>
</html>
Example.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "")
{
Label1.Text = "Please Select a City";
}
else
Label1.Text = "Your Choice is: " + DropDownList1.SelectedValue;
}
I want to grab the selected value from the DropDownLists in my DataGrid when a submit button is clicked, but they always return the first option in the dropdown (approve). How can I get the selected value when using static dropdown items like this?
.aspx code:
<!-- several BoundColumns were here -->
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" CssClass="ally-btn" OnClick="btnSubmit_Click" />
.aspx.cs code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
debugLabel.Text = "";
for (int i = 0; i < dgApprovals.Items.Count; i++)
{
DDLP = (DropDownList)dgApprovals.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
debugLabel.Text += acceptStatus + ", ";
}
}
The debugLabel.Text always ends up being "accept, accept, accept..." even when the DropDownLists have "Reject" selected.
Reproduced and fixed your problem by handling post-back events.
default.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace DropdownClicks
{
public partial class WebForm1 : System.Web.UI.Page
{
static List<string> itemsToInsert = new List<string> { "first", "second", "third" };
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//only do this binding on page load, otherwise you'll "reset" the grid every time there is a postBack.
mydg.DataSource = itemsToInsert;
mydg.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
DropDownList DDLP;
string acceptStatus;
string retVal = "";
for (int i = 0; i < mydg.Items.Count; i++)
{
DDLP = (DropDownList)mydg.Items[i].FindControl("ddlApprovalStatus");
acceptStatus = DDLP.SelectedValue;
retVal += acceptStatus + ", ";
}
lbl_1.Text = retVal;
}
}
}
default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DropdownClicks.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label Text="text" runat="server" ID="lbl_1" />
<asp:DataGrid runat="server" ID="mydg" EnableViewState="true">
<Columns>
<asp:TemplateColumn HeaderText="Actions">
<HeaderStyle CssClass="ProfDataGridHeader" BorderStyle="Solid" BorderWidth="1"></HeaderStyle>
<ItemStyle Width="45%" CssClass="ProfDataGridRow" BorderStyle="Solid" BorderWidth="1"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="ddlApprovalStatus" AppendDataBoundItems="True" runat="server" Width="150px" EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="approve" Text="Approve"></asp:ListItem>
<asp:ListItem Value="reject" Text="Reject"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button Text="click me" runat="server" OnClick="Unnamed_Click" EnableViewState="true" />
</div>
</form>
</body>
</html>
I have some problems here.
How to begin to write GridView and insert data from the database manually one by one based on the GridView header?
I want to create GridView but the structure is not same in the database. So, I want to enter value from the database based on the GridView header. Is it possible?
Because, before this I only retrieved from the database all at once in the GridView. I did not know on how to retrieve based on the header GridView. I am a beginner in the C# language and hope you can give me some example on this? Thank you.
The following what I have done so far:
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Request Date">
<ItemTemplate>
<asp:Label ID="lblReqDate" runat="server" Text='<%# Eval("request_date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="A01"></asp:TemplateField>
<asp:TemplateField HeaderText="A02"></asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Consider data your column has a semi-colon(;) as separator. Then do as below
Add template column with labels in them.
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView3" runat="server" OnRowDataBound="GridView3_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Request Date">
<ItemTemplate>
<asp:Label ID="lblReqDate" runat="server" Text='<%# Eval("request_date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="A01">
<asp:Label ID="lblA01" runat="server" ></asp:Label>
</asp:TemplateField>
<asp:TemplateField HeaderText="A02">
<asp:Label ID="lblA02" runat="server" ></asp:Label>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Now in data grid row bound split data and bind
protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblA01 = (Label)e.Row.FindControl("lblA01");
Label lblA02 = (Label)e.Row.FindControl("lblA02");
string val = DataBinder.Eval(e.Row.DataItem, "product").ToString();
string[] splittedData = val.Split(';');
if (splittedData.Length > 0)
lblA01.Text = splittedData[0];
if (splittedData.Length > 1)
lblA01.Text = splittedData[1];
}
}
}
Hope this helps
When ever i hide or show the Panel, the items i add (dynamically) to the Table are gone, and another thing is that when i try add new Row to the Table, it won't show it, it's overwriting the same Row, why ??.
Here's the CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
DropDownList1.Items.Add(TextBox3.Text);
}
protected void Button3_Click(object sender, EventArgs e)
{
if (Panel1.Visible == true)
Panel1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Panel1.Visible == false)
Panel1.Visible = true;
}
protected void Button4_Click(object sender, EventArgs e)
{
TableCell tdStudentName = new TableCell();
tdStudentName.Text = TextBox1.Text;
TableCell tdStudentCourse = new TableCell();
tdStudentCourse.Text = DropDownList1.SelectedValue;
TableCell tdStudentGrade = new TableCell();
tdStudentGrade.Text = TextBox2.Text;
TableRow tr = new TableRow();
tr.Cells.Add(tdStudentName);
tr.Cells.Add(tdStudentCourse);
tr.Cells.Add(tdStudentGrade);
Table1.Rows.Add(tr);
}
}
}
Here's the Html Source:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Student Name:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Course:"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add Course" />
<br />
<asp:Label ID="Label3" runat="server" Text="Grade:"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="Add" />
<br />
<br />
<asp:Panel ID="Panel1" runat="server" GroupingText="Course Settings" Visible="False">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Add" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Close" />
</asp:Panel>
<br />
<br />
<asp:Table ID="Table1" runat="server" BorderStyle="Solid">
<asp:TableRow runat="server">
<asp:TableCell runat="server">Name</asp:TableCell>
<asp:TableCell runat="server">Course</asp:TableCell>
<asp:TableCell runat="server">Grade</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</form>
</body>
</html>
Here's a preview of how it looks like:
If you add anything dynamically, then you must re-add it on any subsequent post-back. They will not automatically just "be there" on the next post-back.
This requires you to store the fact that the dynamic controls have been created and added, and therefore allows you to detect that on the post-back and add the controls back in again.
It is better (if possible) to add dynamic controls as part of the init stage of the life cycle, as this will mean they will pick up view state information before the load stage.
Edit
In response to the comment by the OP...
Where do i store these controls ? and where do i add them back ? inside Page_Load ?
You don't store the controls... you store the fact that the controls have been added.
The "easiest" way would be to use the ViewState, but that puts you in a catch-22 situation... because the ViewState is not available at the init stage of the life cycle, which is the preferred place to re-add those controls.
Another option would be to "store the fact" within an <asp:HiddenField> which you can check for within the init stage. However you would have to get the value directly from the Request object, as the field would not have the correct .Value at the init stage. You'd do that like...
if (!Page.IsPostBack)
{
string hdnValue = Request[hdnFieldCtrl.UniqueId];
// Recreate controls based on the details you need
}
I'm trying to load/reload a GridView based on the OnSelectedIndexChanged event of a DropDownList. The ddl has AutoPostBack set to true, but still the Grid won't load, unless I encapsulate it within an UpdatePanel. But once I do that, my FileUpload control stops working... What would be the best solution for this problem?
**Edit ** Relevant code:
aspx file
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="upProva" runat="server">
<ContentTemplate>
<%--user control for data selection--%>
<asp:DropDownList ID="ddlAula" runat="server" DataTextField="nmAula" DataValueField="idAula"
CssClass="medio" Enabled="false" AutoPostBack="true" OnSelectedIndexChanged="ddlAula_OnSelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="gvQuestoes" runat="server" AutoGenerateColumns="False" CssClass="gv"
AllowSorting="false" DataKeyNames="idQuestao" OnRowCommand="gvQuestao_RowCommand">
<Columns>
<%--(...)--%>
</Columns>
</asp:GridView>
<asp:Button ID="btnSalvar" runat="server" ToolTip="Salvar" CssClass="botao40 salv40"
OnClick="btnSalvar_Click" ValidationGroup="trabalho" />
<asp:FileUpload ID="fuAnexo" runat="server" CssClass="fileOriginal" />
</asp:Content>
codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnArquivo.OnClientClick = "document.getElementById('" + fuAnexo.ClientID + "').click(); return false;";
txtAnexo.Attributes.Add("onclick", "document.getElementById('" + fuAnexo.ClientID + "').click(); return false;");
fuAnexo.Attributes.Add("onchange", "document.getElementById('" + txtAnexo.ClientID + "').value = this.value;");
}
}
protected void ddlAula_OnSelectedIndexChanged(object sender, EventArgs e)
{
gvQuestoes.DataSource = Questao.CarregarPorAula(Int32.Parse(ddlAula.SelectedValue));
gvQuestoes.DataBind();
}
The DataSource/Databinding is correct (I know because I've added a button to the page, and used the same binding code on the Button _Click event and it works).
You need to rebind the gridview in OnSelectedIndexChanged event. Something like
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Do your processing logic
gridview1.DataSource = new_modified_datasource;
gridview1.DataBind();
}
I found a fairly simple (though not ideal in all cases) with PostBackTrigger:
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="upProva" runat="server">
<ContentTemplate>
<%--user control for data selection--%>
<asp:DropDownList ID="ddlAula" runat="server" DataTextField="nmAula" DataValueField="idAula"
CssClass="medio" Enabled="false" AutoPostBack="true" OnSelectedIndexChanged="ddlAula_OnSelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="gvQuestoes" runat="server" AutoGenerateColumns="False" CssClass="gv"
AllowSorting="false" DataKeyNames="idQuestao" OnRowCommand="gvQuestao_RowCommand">
<Columns>
<%--(...)--%>
</Columns>
</asp:GridView>
<asp:FileUpload ID="fuAnexo" runat="server" CssClass="fileOriginal" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSalvar" />
</Triggers>
</asp:UpdatePanel>
</asp:Content>
Nowhere in your code do you show how you populate ddlAula. So here is my answer: the Page_Load you've shown is abbreviated, and actually you are populating ddlAula there. Furthermore, you are doing it each time, rather than checking IsPostBack. Therefore by the time your eventhandler for ddlAula is hit, the list has been reset and the value you selected is no longer selected.
If my answer is correct, you need to add the check in Page_Load:
if (!IsPostBack)
{
//populate ddlAula
}