Accessing HiddenField inside the datalist - c#

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){ }

Related

ASP.NET: Repeater does not work for me

My C# Code
public partial class Message : System.Web.UI.Page
{
String strconn = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
members();
}
public void members()
{
SqlConnection con = new SqlConnection(strconn);
con.Open();
try
{
string str = "Select Users.Username,Users.Name,ProfilePic.Pathh From Users FULL OUTER JOIN ProfilePic ON Users.username = ProfilePic.Username ORDER BY Users.Sno";
SqlCommand cmd = new SqlCommand(str,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
repMembers.DataSource = ds;
repMembers.DataBind();
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.Dispose();
con.Close();
}
catch(Exception ex) {
lbMembers.Text = ex.ToString();
}
}
}
And My HTML Code
<asp:Repeater ID="repMembers" runat="server" >
<asp:ItemTemplate >
<div style="width:100%; border-bottom:#ffffff 2px solid;"> <asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="60px" Height="60px"/> <asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label><br/><asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label><br/></div>
</asp:ItemTemplate>
</asp:Repeater>
My Table is absolutely correct and is working, i checked it with Grid View. It gives me the "Name","Username", and "Path" Stored.
I checked it with SQL query and displayed it in grid view.
This is the Photo of my table,it is the combination of two tables
Use ItemTemplate instead of asp:ItemTemplate. There's also a typo with the word "Pathh", does this solve your issue?
<ItemTemplate >
<div style="width:100%; border-bottom:#ffffff 2px solid;">
<asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Path") %>' width="60px" Height="60px"/>
<asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label>
<br/>
<asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
<br/>
</div>
</ItemTemplate>

Inserting image on datalist using image name from database

I have an issue trying to display image in my DataList from the database and have access to the database that I'm pulling my images from. But when I run the WebForm the image does not appear, what is wrong in my codes?
<asp:DataList ID="DataList1" runat="server" DataKeyField="dishID" DataSourceID="SqlDataSource1" BorderStyle="Solid" GridLines="Both" RepeatColumns="4" RepeatDirection="Horizontal" Width="1259px" >
<ItemTemplate>
<table class="auto-style1">
<tr><td>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "FoodPictures/" + Eval("dishImage") %>' />
This is how I'm retrieving from the database:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(_connStr);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Dish";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
conn.Close();
DataList1.DataSource = dt;
DataList1.DataBind();
conn.Close();
}
I think Your Page do not get image on proper path....
use
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "../FoodPictures/" + Eval("dishImage") %>' />
Or
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "~/FoodPictures/" + Eval("dishImage") %>' />
Try this..
Assuming if dishImage is a name like imagename.jpg stored in database then try Convert.ToString(Eval("dishImage")) like:
<asp:Image ID="Image1" ImageUrl='<% # "~/FoodPictures/" + Convert.ToString(Eval("dishImage")) %>' runat="server" />

Gridview is not displaying while i run my code

I want to display three column field as dropdownlist and other in textbox format.I have wrote the code to display the dropdownlist value from my database but its not working.I have attached my code for your referal
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="FacultyName">
<ItemTemplate>
<asp:Label ID="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false" />
<asp:DropDownList ID="ddlfaculty" runat="server" OnSelectedIndexChanged="ddlfaculty_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("subject") %>>' Visible="false" />
<asp:DropDownList ID="ddlsubject" runat="server" OnSelectedIndexChanged="ddlsubject_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("subject") %>>' Visible="false" />
<asp:DropDownList ID="ddlsubject" runat="server" OnSelectedIndexChanged="ddlsubject_SelectedIndexChanged1"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("sethour") %>>' Visible="false" />
<asp:TextBox ID="ddlsethour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblcount" runat="server" Visible="false" />
<asp:TextBox ID="Count" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind:
public partial class transhonorarium : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlfaculty_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter cmd = new SqlDataAdapter("select facultyname from faculty", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
Gv1.DataSource = dt;
Gv1.DataBind();
}
}
protected void ddlsubject_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter cmd = new SqlDataAdapter("select subject from assign where facultyname=#facultyname", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
Gv1.DataSource = dt;
Gv1.DataBind();
}
}
}
You need to change one thing here.
AutoGenerateColumns = true. Because of this, you will be able to see the columns assigned and its data.
Secondly,
You need to Bind your Gridview as required on Page_load or somewhere you want. Here is for page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Gv1.DataSource = Somesource;
Gv1.DataBind();
}
}
See the Bind Data
public void BindData()
{
SqlCommand comd = new SqlCommand("SELECT * FROM Yourtablename", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GV1.DataSource = dt;
GV1.DataBind();
}
Hope that helps
Call the DataBind() Method of your Gridview when your data changes.
I'd do something like this:
protected override void OnPreRender(Eventargs e)
{
base.OnPreRender(e);
GV1.DataBind();
}
in order to fill your dropdown lists ,you should implement _RowDataBound event and to update dataset bases on your selection you should also implement RowCommand event for your dropdown objects.
btw. in ddlsubject_SelectedIndexChanged, you also need to add parameter to your sql command to get your sql string working ,
hope this helps.

Get Value from dropdown list and add it to a Gridview

I have two dropdown lists in asp.net which are generated from a database. When the user selected a value from the first dropdown list, the second dropdown list will be generated based on this value.
I also have a gridview with has a add row, delete and save function. Within each cell of the gridview are textboxes which are self generated by the add row function.
What I want to do is to have a add selected value button from the dropdown list and for the value of the second dropdown list to be added into the first cell of the gridview.
However, if there are muliple gridview rows generated, then a option should appear asking which row the value should be inserted into.
Please can I get some help on this?
Below is the ASP.net
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="workout">
<div class="exerciseDD">
<fieldset class="exercise">
<legend>Exercise List</legend>
<div style="text-align: justify">
To begin choose the exercise number you wish to add an exercise too. Then use
the dropdown menu to select the exercise you wish to use in your workout.
Finally click add to insert the exercise into the workout.
<br />
<br />
<asp:Label ID="Label3" runat="server" CssClass="bold"
Text="Choose an exercise number:"></asp:Label>
<br />
<asp:DropDownList ID="ExerNo" runat="server">
<asp:ListItem Selected="True">1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
<asp:ListItem>6</asp:ListItem>
<asp:ListItem>7</asp:ListItem>
<asp:ListItem>8</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Label ID="MuscleGDD" runat="server" CssClass="bold" Text="Muscle Group:"></asp:Label>
<br />
<asp:DropDownList ID="MuscleDD" runat="server" AutoPostBack="True"
Height="22px" onselectedindexchanged="MuscleDD_SelectedIndexChanged"
Width="100%">
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label4" runat="server" CssClass="bold" Text="Exercise Name:"></asp:Label>
<br />
<asp:DropDownList ID="ExerciseDD" runat="server" AutoPostBack="True"
Height="22px" onselectedindexchanged="ExerciseDD_SelectedIndexChanged"
Width="100%">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="Add" runat="server" Text="Add Exercise" onclick="Add_Click" />
<br />
<asp:Label ID="Label5" runat="server" CssClass="bold"
Text="Exercise Description:"></asp:Label>
<br />
<asp:Label ID="Exerdes" runat="server"></asp:Label>
</div>
</fieldset>
</div>
<div class="createWO">
<fieldset class="create">
<legend>Create Workout</legend>
<asp:Label ID="LabelUserId" runat="server" Visible="True"></asp:Label>
<br />
<strong>Workout Name:</strong> <asp:TextBox ID="WorkName" runat="server"></asp:TextBox>
<div>
<asp:Label ID="CurrentDate" runat="server" />
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDeleting="grvWorkout_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:BoundField DataField="Userid" HeaderText="User ID" Visible="false"/>
<asp:TemplateField HeaderText="Exercise Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Repetition">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:gridview>
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
<br />
<br />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Below is the Code behind. The code contains the add row, delete and save function. The code also contains the functionality to populate the dropdown lists:
private void SetInitialRow()
{
//Sets the initial row of the gridview
}
private void AddNewRowToGrid()
{
//Adds a new row and placing any data back into the gridview
}
private void SetPreviousData()
{
//temp save of the dat
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable MuscleG = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Muscle_id], [MuscleName] FROM [MuscleGroup]", con);
adapter.Fill(MuscleG);
MuscleDD.DataSource = MuscleG;
MuscleDD.DataTextField = "MuscleName";
MuscleDD.DataValueField = "Muscle_id";
MuscleDD.DataBind();
}
//MuscleDD.Items.Insert(0, new ListItem("Select Muscle Name", "0"));
}
if (!Page.IsPostBack)
{
SetInitialRow();
}
CurrentDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
}
protected void MuscleDD_SelectedIndexChanged(object sender, EventArgs e)
{
int muscleid = Convert.ToInt32(MuscleDD.SelectedValue);
DataTable exercises = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Exercise_id], [ExerciseName] FROM [Exercise] WHERE [Muscle_id] = " + muscleid, con2);
adapter.Fill(exercises);
ExerciseDD.DataSource = exercises;
ExerciseDD.DataTextField = "ExerciseName";
ExerciseDD.DataValueField = "Exercise_id";
ExerciseDD.DataBind();
}
//ExerciseDD.Items.Insert(0, new ListItem("Select Exercise", "0"));
}
protected void ExerciseDD_SelectedIndexChanged(object sender, EventArgs e)
{
int exerciseid = Convert.ToInt32(ExerciseDD.SelectedValue);
using (SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
con3.Open();
string cmdStr = "SELECT [Exercise_id], [ExerDesc] FROM [ExerciseDescription] WHERE [Exercise_id] = '" + exerciseid +"'";
SqlCommand Des = new SqlCommand(cmdStr, con3);
SqlDataReader reader = Des.ExecuteReader();
reader.Read();
Exerdes.Text = reader["ExerDesc"].ToString();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Saves data in gridview to database
}
//A method that returns a string which calls the connection string from the web.config
private string GetConnectionString()
{
}
//A method that Inserts the records to the database
private void InsertRecords(StringCollection sc)
{
//Inserts the records into the database
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
private void SetRowData()
{
//Set data in temp table
}
protected void grvWorkout_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Deletes the row
}
//This function relates to the button I wish to insert the value of the dropdown menu into the gridview.
protected void Add_Click(object sender, EventArgs e)
{
//Add dropdown value
}
Here is a quick & dirty sample I made based on your requirement to get you started.
You can select a car make & get selected models
You can add rows to the gridview on button click
You can select the stock model's properties on checkbox click of gridview
Aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="gridTest.aspx.cs" Inherits="WebApplication1.Gridview" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Make:
<asp:DropDownList ID="ddlMake" runat="server" AppendDataBoundItems="True" AutoPostBack="True"
OnSelectedIndexChanged="ddlMake_SelectedIndexChanged">
<asp:ListItem Text=" - Select -" Value=""></asp:ListItem>
</asp:DropDownList>
<br />
Model:
<asp:DropDownList ID="ddlModels" runat="server">
</asp:DropDownList>
<br />
<br />
<h2>
Accessories
<asp:Button ID="btnAddConsignment" runat="server" OnClick="btnAddConsignment_Click"
Text="Add Consignment" />
</h2>
<asp:GridView ID="gvItems" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Consignment No.">
<ItemTemplate>
<%# Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Color">
<itemtemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tires">
<itemtemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NOS">
<itemtemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</itemtemplate>
</asp:TemplateField>
<asp:TemplateField>
<itemtemplate><asp:CheckBox ID="cbSameAsStock" runat="server" AutoPostBack="True"
oncheckedchanged="cbSameAsStock_CheckedChanged" Text="Same as stock?" /></itemtemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class Gridview : System.Web.UI.Page
{
public class Make
{
public int Id { get; set; }
public string Name { get; set; }
public List<Make> GetMake()
{
return new List<Make>()
{
new Make { Id = 1, Name = "Ford" },
new Make { Id = 2, Name = "BMW" },
new Make { Id = 3, Name = "Lamborghini" }
}.ToList();
}
}
public class Models
{
public int ModelId { get; set; }
public int MakeId { get; set; }
public string Name { get; set; }
public List<Models> GetModels()
{
return new List<Models>()
{
new Models { ModelId=1, MakeId=1, Name="Ford Truck 1"},
new Models { ModelId=2, MakeId=1, Name="Ford Truck 2"},
new Models { ModelId=3, MakeId=1, Name="Ford Truck 3"},
new Models { ModelId=4, MakeId=3, Name="Gollarado"},
new Models { ModelId=5, MakeId=3, Name="Murcillago"}
};
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Temporary data fetched through a list. In production you will fetch data from the database
Make make = new Make();
ddlMake.DataSource = make.GetMake();
ddlMake.DataTextField = "Name";
ddlMake.DataValueField = "Id";
ddlMake.DataBind();
if(ViewState["dt"]!=null)
{
DataTable dt = ViewState["dt"] as DataTable;
gvItems.DataSource = dt;
}
}
}
protected void ddlMake_SelectedIndexChanged(object sender, EventArgs e)
{
// Filter second dropdown list
Models model = new Models();
ddlModels.DataSource = model.GetModels().Where(s => s.MakeId == int.Parse(ddlMake.SelectedValue));
ddlModels.DataTextField = "Name";
ddlModels.DataValueField = "ModelId";
ddlModels.DataBind();
}
protected void btnAddConsignment_Click(object sender, EventArgs e)
{
// Bind gridview to temporary data & store inside viewstate
DataTable dt = null;
if (ViewState["dt"] == null)
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("Color", typeof(string)));
dt.Columns.Add(new DataColumn("Tires", typeof(string)));
dt.Columns.Add(new DataColumn("NOS", typeof(string)));
dt.Columns["Id"].AutoIncrement = true;
dt.Columns["Id"].AutoIncrementSeed = 1;
}
else
dt = ViewState["dt"] as DataTable;
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
gvItems.DataSource = dt;
gvItems.DataBind();
ViewState["dt"] = dt;
}
protected void cbSameAsStock_CheckedChanged(object sender, EventArgs e)
{
// Get your checkbox from gridview's selected row
CheckBox cbTemp = sender as CheckBox;
if (cbTemp != null)
{
// If selected, append selected model name to textboxes
if (cbTemp.Checked)
{
var selectedModel = ddlModels.SelectedItem.Text; // your selected car model
GridViewRow gr = ((CheckBox) sender).NamingContainer as GridViewRow;
if (gr != null)
{
TextBox txt1 = gr.FindControl("TextBox1") as TextBox;
TextBox txt2 = gr.FindControl("TextBox2") as TextBox;
TextBox txt3 = gr.FindControl("TextBox3") as TextBox;
txt1.Text = "Same as stock "+ selectedModel;
txt2.Text = "Same as stock " + selectedModel;
txt3.Text = "Same as stock " + selectedModel;
}
}
}
}
}
}

How to use the DropDownList's SelectedIndexChanged event

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;

Categories