I have two DropDownLists in my webform and when I select a value in the first dropdownlist, I would like a related value to be automatically selected in the second dropdownlist.
This is what I currently have:
<table>
<tr>
<td>
<asp:Label ID="lbmanu" runat="server" Text="Furniture Manufacturer :
"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddmanu" runat="server"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Sql_fur_model_manu" runat="server"
ConnectionString="<%$ ConnectionStrings:conStr %>"
SelectCommand="SELECT DISTINCT [manufacturer] FROM
[furniture_manufacturer]">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbtype" runat="server" Text="Furniture Type :
"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddtype" runat="server" AutoPostBack="True">
</asp:DropDownList>
</td>
</tr>
</table>
Code Behind :
protected void ddmanu_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select furniture from furniture_model where manufacturer='" +
ddmanu.SelectedValue.ToString() + "'";
con.Open();
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
ddtype.DataTextField = "manufacturer";
ddtype.DataValueField = "furniture";
ddtype.DataBind();
}
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
I think this is the culprit:
cmd = new SqlCommand(query, con);
DataTable dt = Select(query);
cmd.ExecuteNonQuery();
ddtype.DataSource = dt;
I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":
cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();
Or you can create a DataTable as explained here:
cmd = new SqlCommand(query, con);
SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);
ddtype.DataSource = listTable;
Related
I am trying to create my own online quiz website using ASP C#.
I tried to bind the question from database into gridview and set the page size of the gridview to 1.
And then I tried to pull the answers option (4 option) into radioButton.
But when I tried to move from the 1 page of gridview to another page, the checked value lost. I know thats because of when we changed the gridview page, it will do a postback.
My Questions are:
Why I can't access my RadioButton from CodeBehind? Is it because of inside the Updatepanel ?
Is it possible if we want to do a page index change in gridview without postback? Or,
is there another option to make my RadioButton checked value not lost when changing to the next page (next question) ?
here are my code :
**quiz.aspx :**
<asp:UpdatePanel ID="upd1" runat="server">
<ContentTemplate>
<asp:GridView ID="grdquestions" runat="server" EnableViewState="true" EnableSortingAndPagingCallbacks="false" OnPageIndexChanging="grdquestions_PageIndexChanging" AutoGenerateColumns="false" DataKeyNames="QuestionId" Width="100%" AllowPaging="True" AllowCustomPaging="False" PageSize="1" ViewStateMode="Enabled">
<Columns>
<asp:TemplateField HeaderText="DOJO eQuiz">
<ItemTemplate>
<table class="tableclass" id='<%#Eval("QuestionId") %>'>
<tr>
<td><b>Question : <%#Eval("Question") %></b>
<asp:HiddenField ID="hdnquestionId" runat="server" />
</td>
</tr>
<tr>
<td>
<table>
<tr style="margin-top: 10px;">
<td>
<table class="tblOptions">
<tr>
<td>
<asp:RadioButton ID="rdOption1" AutoPostBack="true" runat="server" Text='<%#Eval("Option1") %>' GroupName="chcbox" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rdOption2" runat="server" AutoPostBack="true" Text='<%#Eval("Option2") %>' GroupName="chcbox" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rdOption3" runat="server" AutoPostBack="true" Text='<%#Eval("Option3") %>' GroupName="chcbox" />
</td>
</tr>
<tr>
<td>
<asp:RadioButton ID="rdOption4" runat="server" Text='<%#Eval("Option4") %>' GroupName="chcbox" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lbquestionstatus" runat="server"></asp:Label>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle HorizontalAlign="Center" CssClass="GridPager" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
**quiz.aspx.cs**
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
if (!Page.IsPostBack)
{
BindGrid();
}
else
{
}
}
}
public void BindGrid()
{
var sess = Session["username"].ToString();
string a = sess.Substring(sess.Length - 1);
SqlDataAdapter adp = new SqlDataAdapter("select * from dojoquiz order by " + a + "", ConfigurationManager.ConnectionStrings["dashboardConnectionString"].ToString());
adp.Fill(dt);
grdquestions.DataSource = dt;
grdquestions.DataBind();
}
protected void grdquestions_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButtonList rdlstOptions = (RadioButtonList)e.Row.FindControl("rdlstOptions");
HiddenField hdnquestionId = (HiddenField)e.Row.FindControl("hdnquestionId");
if (rdlstOptions != null && hdnquestionId != null)
{
DataRow[] result = dt.Select("questionid=" + (Convert.ToInt32(hdnquestionId.Value)));
DataView view = new DataView();
view.Table = dt;
view.RowFilter = "questionid=" + (Convert.ToInt32(hdnquestionId.Value));
if (view.Table.Rows.Count > 0)
{
DataTable dt1 = new DataTable();
dt1 = view.ToTable();
}
}
}
}
protected void grdquestions_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdquestions.PageIndex = e.NewPageIndex;
this.BindGrid();
}
Thank you for any help and suggestions.
If the sql query is not change, then don't do DataBind() on post back, but you still need to give him the data source to get the data. So your code must be as:
protected void Page_Load(object sender, EventArgs e)
{
BindGrid();
}
public void BindGrid()
{
var sess = Session["username"].ToString();
string a = sess.Substring(sess.Length - 1);
SqlDataAdapter adp = new SqlDataAdapter("select * from dojoquiz order by " + a + "", ConfigurationManager.ConnectionStrings["dashboardConnectionString"].ToString());
adp.Fill(dt);
grdquestions.DataSource = dt;
if (!Page.IsPostBack)
grdquestions.DataBind();
}
Its not possible with out post back to change page or do thinks on GridView, but if you make it correct this is not an issue.
This question already has answers here:
DataBinding: 'System.Data.DataRowView' does not contain a property with the name
(4 answers)
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'ProductID'
(3 answers)
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'userid'
(1 answer)
Closed 3 years ago.
I have problems on my dropdown function. The dropdown function suppose to get the values from the database. I think the problem is on the sql select command, but I am new to this kind of stuff (asp.net and sql). can someone help me please, thank you in advance.
this is the SQL DataSourceID
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:*****ConnectionString %>" SelectCommand="SELECT TOP 10
C.CASE_KEY, C.DEPARTMENT_CASE_NUMBER, D.DEPARTMENT_NAME, O.OFFENSE_DESCRIPTION AS CHARGE, LAB_CASE,
OFFENSE_DATE
FROM TV_LABCASE C
INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE
INNER JOIN TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE
ORDER BY CASE_DATE DESC
"></asp:SqlDataSource>
Code for the input fields
<table class="style2" >
<tr>
<td class="style3" >Department Case #</td>
<td> <asp:TextBox ID="TextBox1" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Department</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="18px" Width="166px" Enabled="False">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Charge</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="25px" Width="165px" Enabled="False">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Lab Case #</td>
<td><asp:TextBox ID="TextBox4" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Incident Report Date</td>
<td><asp:TextBox ID="TextBox5" runat="server" Enabled="False" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
</table>
ASP.NET C#(server-side code)
protected void Page_Load(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=A**SE****D***\MSSQL****;Initial Catalog=****;User
ID=****;Password=****";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand cmd = new SqlCommand("select * from TV_LABCASE", cnn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
DropDownList2.DataTextField = "OFFENSE_DESCRIPTION";
DropDownList2.DataValueField = "OFFENSE_CODE";
DropDownList2.DataBind();
}
Code for the input fields enable the value is true. TRY IT
<table class="style2" >
<tr>
<td class="style3" >Department Case #</td>
<td> <asp:TextBox ID="TextBox1" runat="server" Enabled="true" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Department</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
Height="18px" Width="166px" Enabled="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Charge</td>
<td>
<asp:DropDownList ID="DropDownList2" runat="server"
Height="25px" Width="165px" Enabled="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style3">Lab Case #</td>
<td><asp:TextBox ID="TextBox4" runat="server" Enabled="true" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
<tr>
<td class="style3">Incident Report Date</td>
<td><asp:TextBox ID="TextBox5" runat="server" Enabled="true" ontextchanged="btnCancel_Click"></asp:TextBox></td>
</tr>
</table>
ASP.NET C#(server-side code)
protected void Page_Load(object sender, EventArgs e)
{
string connetionString;
SqlConnection cnn;
connetionString = #"Data Source=A**SE****D***\MSSQL****;Initial Catalog=****;User
ID=****;Password=****";
cnn = new SqlConnection(connetionString);
cnn.Open();
SqlCommand cmd = new SqlCommand(#"SELECT * from TV_LABCASE C Left join TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE Left join TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE", cnn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = dt;
DropDownList2.DataBind();
DropDownList2.DataTextField = "OFFENSE_DESCRIPTION";
DropDownList2.DataValueField = "OFFENSE_CODE";
DropDownList2.DataBind();
}
replace your command query to join TV_DEPTNAME table
SqlCommand cmd = new SqlCommand("select C.*, D.DEPARTMENT_NAME from TV_LABCASE C INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE, ", cnn);
or change your datasource to
DropDownList1.DataSource = SqlDataSource1;
DropDownList1.DataBind();
DropDownList1.DataTextField = "DEPARTMENT_NAME";
DropDownList1.DataValueField = "DEPARTMENT_CODE";
DropDownList1.DataBind();
DropDownList2.DataSource = SqlDataSource1;
DropDownList2.DataBind();
DropDownList2.DataTextField = "CHARGE";
and update your asp:SqlDataSource config
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:*****ConnectionString %>"
SelectCommand="SELECT TOP 10
C.CASE_KEY, C.DEPARTMENT_CASE_NUMBER, D.DEPARTMENT_NAME, O.OFFENSE_DESCRIPTION AS CHARGE, LAB_CASE,
OFFENSE_DATE, C.DEPARTMENT_CODE
FROM TV_LABCASE C
INNER JOIN TV_DEPTNAME D ON C.DEPARTMENT_CODE = D.DEPARTMENT_CODE
INNER JOIN TV_OFFENSE O ON C.OFFENSE_CODE = O.OFFENSE_CODE
ORDER BY C.CASE_DATE DESC"
></asp:SqlDataSource>
Heres the dropdownlist and datalist code
<div>
Sort by Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>All</asp:ListItem>
<asp:ListItem>Decoration</asp:ListItem>
<asp:ListItem>Catering</asp:ListItem>
<asp:ListItem>Entertainment</asp:ListItem>
<asp:ListItem>Sound</asp:ListItem>
<asp:ListItem>Others</asp:ListItem>
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server"
GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal"
Width="1000px" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<table class="nav-justified">
<tr>
<td class="text-center">
<strong>
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("serName") %>'></asp:Label>
</strong>
</td>
</tr>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="179px"
ImageUrl='<%# Eval("serImg") %>' Width="191px"/>
</td>
</tr>
<tr>
<td>
<strong>
<asp:Label ID="Label2" runat="server" Text="Rs"></asp:Label>
<asp:Label ID="Label3" runat="server"
Text='<%# Eval("sprice") %>'>
</asp:Label>
</strong>
</td>
</tr>
<tr>
<td class="text-center">
<asp:Button ID="Button1" runat="server" Text="Details" />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:DataList>
</div>
Here is the .cs code. Its purpose is to filter the data in the list according to the selected category in the dropdown list
protected void Page_Load(object sender, EventArgs e)
{
String conString = ConfigurationManager.ConnectionStrings["regcon"].ConnectionString;
string query = "select * from addService where serCategory=#cat";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.AddWithValue("#cat", DropDownList1.SelectedItem.Value);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
}
}
I get the error "Both DataSource and DataSourceID are defined on 'DataList1'. Remove one definition." when i run it.Removing the Datalist1 or DataSourceID would give an error.How do i fix this?
The problem is, on the datalist you have a datasource
DataSourceID="SqlDataSource1"
Then you also apply a data source in the code behind
DataList1.DataSource = ds;
You can't do both. You could remove the existing one in code then apply a new one if you want.
I'm using a Datalist to show countries list each record having a Gridview containing a list of states and each state having a Dropdownlist for cities. I am using a hidden field to get the ID of country to retrieve the name of state for every record by using Eval("C_ID") in the hidden field. But it raises ArgumentOutOfRangeException. I'm not able to know what I'm doing wrong.
Here is the code for Datalist:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" onitemdatabound="DataList1_ItemDataBound" >
<ItemTemplate>
<table border="1px">
<tr>
<td>
<%#Eval("C_Name") %><br />
<asp:HiddenField ID="HiddenField1" Value='<%#Eval("C_ID") %>' runat="server" />
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="State Cities">
<ItemTemplate >
<asp:CheckBox ID="CheckBox1" runat="server" />
<%#Eval("S_Name") %>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
and this is code behind:
public partial class AdvancedTable : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("select * from Country", con);
con.Open();
da.Fill(ds, "Country");
con.Close();
DataList1.DataSource = ds;
DataList1.DataBind();
}
}
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = new SqlCommand("select * from State where C_ID='"+((HiddenField)DataList1.Items[e.Item.ItemIndex].FindControl("HiddenField1")).Value+"'",con);
con.Open();
da2.Fill(ds, "State");
con.Close();
((GridView)e.Item.FindControl("GridView1")).DataSource = ds.Tables["State"];
((GridView)e.Item.FindControl("GridView1")).DataBind();
}
}
Perhaps, instead of DataList1.Items[e.Item.ItemIndex].FindControl("HiddenField1")
Just use e.Item.FindControl("HiddenField1")
Instead, you can do the following:
<asp:DropDownList ID="DropDownList1" runat="server" DataSource="<%# GetList((int)Eval("C_ID"))%>">
</asp:DropDownList>
In the code Behind
protected DataTable GetList(int id){ }
I currenty have a stored procedure that I am running and hoping to bind the data from the sp with my list view. However, I am unsure of how to go upon doing this.
Here is my current code. I was thinking it was similar to databinding a gridview but got lost doing it.
HTML
<asp:ListView runat="server">
<LayoutTemplate>
<table>
<tr style="background-color:green">
<th><asp:LinkButton ID="lnkid" runat="server">Role ID</asp:LinkButton></th>
<th><asp:LinkButton ID="lnkdesc" runat="server">Role Description</asp:LinkButton></th>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><asp:Label runat="server" ID="lblroleid">Role ID</asp:Label></td>
<td><asp:Label runat="server" ID="lblroledesc">Role Desc></asp:Label></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color:Aqua">
<td><asp:Label runat="server" ID="lblroleid">Role ID</asp:Label></td>
<td><asp:Label runat="server" ID="lblroledesc">Role Desc</asp:Label></td>
</tr>
</AlternatingItemTemplate>
</asp:ListView>
c#
protected void roles()
{
txtSearch.Focus();
string[] queryvalue = txtSearch.Text.Split(' ');
SqlConnection myconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Rollup2ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "USP_GET_USER_ROLES";
cmd.Connection = myconn;
cmd.Parameters.Add("#NUID", SqlDbType.VarChar).Value = queryvalue[0].ToString();
myconn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
myconn.Close();
myconn.Dispose();
}
This should help you out
ASP.NET Populate ListView with Stored Procedure
<asp:SqlDataSource ID="sdsYourData" Runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="Server=(local);Database=Northwind;Integrated Security=SSPI;"
SelectCommand="dbo.YourStoredProcName"
<SelectParameters>
<asp:Parameter Name="Param1" Type="String" />>
</SelectParameters>
</asp:SqlDataSource>