I'm new to asp.net and I need some help, please. I'm using c# and sql.
What I want to do is the following: I have a details view where I can use it to add Employees and save it to my database in Employee table. Within the details view, I'v created a template field for dept_id (this field is a foreign key). I want to make it as a drop down list where you can choose the department name (which is in the Department table) instead of entering the department id. I'm very stick in this. Any help will be appreciated.
This is the .aspx
<asp:TemplateField HeaderText="Dept_id" SortExpression="Dept_id">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="ddlSqlDataSource"
DataTextField="dept_name" DataValueField="dept_id" SelectedValue='<%# Bind("dept_id") %>'>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="ddlSqlDataSource"
DataTextField="dept_name" DataValueField="dept_id" SelectedValue='<%# Bind("dept_id") %>'>
</asp:DropDownList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Dept_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
I'm not sure what should I write inside the dropdownlist control and what to write in its SqlDataSource (ddlSqlDataSource)
<asp:SqlDataSource ID="ddlSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [dept_name] FROM [Department]">
</asp:SqlDataSource>
Could any one help please!
Thanks in advance.
----------
Issues Solved!
Thanks all!
Here is the modified code:
<asp:TemplateField HeaderText="Dept_id" SortExpression="Dept_id">
<ItemTemplate>
<%#Eval("dept_id") %>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="ddlDept" runat="server" DataSourceID="ddlSqlDataSource"
DataTextField="dept_name" DataValueField="dept_id" SelectedValue='<%# Bind("Dept_id") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="ddlSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT dept_id, dept_name FROM Department ">
</asp:SqlDataSource>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Dept_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And I added these to lines to code behind:
protected void DetailsView2_DataBound(object sender, EventArgs e)
{
DropDownList ddlDept = (DropDownList)DetailsView2.FindControl("ddlDept");
ddlDept.Items.Insert(0, new ListItem("Select department"));
}