I am using three DropDownLists in a page. And I am binding data to DDL1(DropDownList1) on pageload using if(!Page.IsPostBack) condition too. And on DDL1 selectedIndexChanged Event I am binding data to DDL2 and its working fine. But when I try to do the same to DDL3 & DDL2 (Like binding data to DDL2 on SelectedIndexChanged Event of DDL2) always DDL2 selects the first item only if I select random also DDL2 still goes first item. Here All 3 DDLs are AutoPostback-true, Vistate-Enabled
Here is my code:
ASPX - Code..
<form id="form1" runat="server">
<div>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True">
<asp:ListItem Value="0">Select</asp:ListItem>
</asp:DropDownList>
<br />
</div>
</form>
.CS Code...
public partial class getcolumns : System.Web.UI.Page
{
private SqlConnection con;
private SqlDataAdapter da;
private DataTable dt;
private DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string query = " SELECT name, dbid FROM sys.sysdatabases where dbid > 4 order by name ";
con = new SqlConnection(ConfigurationManager.AppSettings["godb"].ToString());
da = new SqlDataAdapter(query, con);
dt = new DataTable();
ds = new DataSet();
da.Fill(dt);
DropDownList1.DataSource = dt.DefaultView.ToTable(true, "name", "dbid");
//DropDownList1.DataValueField = "dbid";
DropDownList1.DataTextField = "name";
DropDownList1.DataBind();
}
catch (Exception) { }
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList2.Items.Clear();
string query = " SELECT TABLE_CATALOG, TABLE_NAME FROM " + DropDownList1.SelectedItem + ".INFORMATION_SCHEMA.tables ";
con = new SqlConnection(ConfigurationManager.AppSettings["godb"].ToString());
da = new SqlDataAdapter(query, con);
dt = new DataTable();
ds = new DataSet();
da.Fill(ds);
DropDownList2.DataSource = ds; // dt.DefaultView.ToTable(true, "TABLE_NAME", "TABLE_CATALOG");
//DropDownList2.DataValueField = "TABLE_CATALOG";
DropDownList2.DataTextField = "TABLE_NAME";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem("--Select--", "0"));
}
catch { }
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
DropDownList3.Items.Clear();
string query = " SELECT TABLE_NAME, COLUMN_NAME FROM " + DropDownList1.SelectedItem + ".INFORMATION_SCHEMA.columns where TABLE_NAME = '" + DropDownList2.SelectedItem + "' ";
con = new SqlConnection(ConfigurationManager.AppSettings["godb"].ToString());
da = new SqlDataAdapter(query, con);
dt = new DataTable();
da.Fill(dt);
DropDownList3.DataSource = dt.DefaultView.ToTable(true, "TABLE_NAME", "COLUMN_NAME");
//DropDownList3.DataValueField = "TABLE_NAME";
DropDownList3.DataTextField = "COLUMN_NAME";
DropDownList3.DataBind();
}
catch (Exception) { }
}
}
Edit :-
It worked well when I Ignore the 'DataValueField' of DDLs
Thank All to your support...
This could be multiple autopostback events, so when it fires firstly ddl1 goes and overwrites selected item in second one. When second event comes it is reset to default state.
You could try using same event method on both and depending on the caller populate stuff.
Make use of these two (object sender, EventArgs e) :D
Try using this code, its working Fine for me.
aspx
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" >
</asp:DropDownList>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="True" >
</asp:DropDownList>
</div>
</form>
.cs
public List<string> list1 { get; set; }
public List<string> list2 { get; set; }
public List<string> list3 { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
list1 = new List<string> { "a", "b", "c" };
DropDownList1.DataSource = list1;
DropDownList1.DataBind();
}
catch (Exception) { }
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
list2 = new List<string> { "1a", "1b", "1c" };
DropDownList2.DataSource = list2;
DropDownList2.DataBind();
}
catch { }
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
list3 = new List<string> { "2a", "2b", "2c" };
DropDownList3.DataSource = list3;
DropDownList3.DataBind();
}
catch (Exception) { }
}
I Just removed your default options in the dropdowns and removed viewstatemode and use your databinding instead of lists.
Related
I've created a dropdownlist, and tried clicking on the first selection but there was no firing of the SelectedIndexChanged event. However, it worked perfectly fine for the rest of the options in the dropdownlist.
Here are my codes:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string member = (String)Session["ssmem"];
if (!IsPostBack)
{
if (Session["ssmem"] == null)
Response.Redirect("LoginforAccess.aspx");
else
{
Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "no-cache");
//if go back then must log in --2
}
//Dropdownlist
string strConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//STEP1 : Define a connection to Database
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strcommand = "Select Username from [User] WHERE (UsergroupID = (SELECT UsergroupID FROM [User] AS User_1 WHERE (Username = #user)))";
SqlCommand cmd = new SqlCommand(strcommand, myConnect);
// cmd.Parameters.AddWithValue("#usergrp", groupid);
cmd.Parameters.AddWithValue("#user", member);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "Username";
DropDownList1.DataValueField = "Username";
DropDownList1.DataBind();
reader.Close();
myConnect.Close();
}
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Session["ssmem"] != null)
MasterPageFile = "User.master";
//change the master page --1
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//chosen name to display stats
string choseuser = "";
choseuser = DropDownList1.SelectedItem.Text;
Response.Redirect("Substats.aspx?choseuser=" + choseuser);
}
}
Source view for dropdownlist:
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px" Height="35px"
AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
ViewStateMode="Enabled">
</asp:DropDownList>
We have to add first item as title to the dropdownlist,
and instead of using datasource used dr.Read() in while loop for adding the items on dropdownlist.
This problem occurs because in dropdownlist first item is selected bydefault and it is not reflected on selection
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ViewStateMode="Enabled">
<asp:ListItem>Select College</asp:ListItem>
<!--Add one item as title into dropdownlist in edit item of dropdownlist-->
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("hello");
try
{
string sel = "select name from websites";
SqlCommand cmd = new SqlCommand(sel,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
/* DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();*/
while (dr.Read())//used dr.read() instead of datasource
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("select url from websites where name = #itm", con);
cmd.Parameters.AddWithValue("#itm", DropDownList1.SelectedItem.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
Response.Redirect(dr["url"].ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
I want to get what I write in the textbox but always get the "" string. I can't find the value when I type something else into the textboxT_T.
Here is the Gridview code:
<div style="margin:0 auto;width:900px;">
<asp:Label ID="USER_header" runat="server"
Text="一.先新增用戶" CssClass="=text-center"></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter = "true" Width="900" OnDataBound = "OnDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="工號" SortExpression="BS_ID">
<ItemTemplate>
<asp:Label ID="lblBSID" runat="server"
Text='<%# Eval("BS_ID") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_ID_tb" runat="server"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="中文姓名" SortExpression="BS_NAME_CHT">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_CHT" runat="server"
Text='<%# Eval("BS_NAME_CHT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_CHT_tb" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="英文姓名" SortExpression="BS_NAME_ENG">
<ItemTemplate>
<asp:Label ID="lblBS_NAME_ENG" runat="server"
Text='<%# Eval("BS_NAME_ENG") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="BS_NAME_ENG_tb" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="部門" SortExpression="BS_DEPT">
<ItemTemplate>
<asp:Label ID="lblBS_DEPT" runat="server"
Text='<%# Eval("BS_DEPT") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" Width="200" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:LinkButton ID="btnInsert" runat="server"
onclick="lbInsert_Click" Text="新增" CommandName="Insert"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
Here is the complete code:
private DataSet _dataSet;
private DataSet _dataSetHKTEL;
private DataSet _datasetHKMOBILE;
private string _value;
protected void Page_Load(object sender, EventArgs e)
{
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
//if (Session["key_pass"] == null)
//{
// Response.Write("<script>alert('YOUR ACCESS DENY! 你沒有權限進入此頁面');location.href='Default.aspx';</script>");
//}
}
private void Viewtable()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 BS_ID,BS_NAME_CHT,BS_NAME_ENG,BS_DEPT FROM BS_USER ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateDataTable();
conn.Open();
da1.Fill(finaldata);
this._dataSet = new DataSet();
this._dataSet.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewItnlHKTel()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_TEL_NO,DA_USER FROM DA_ITNL_HK_TEL ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateTable();
conn.Open();
da1.Fill(finaldata);
this._dataSetHKTEL = new DataSet();
this._dataSetHKTEL.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private void ViewITNLHKMOBILE()
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
string query = "SELECT TOP 2 DA_PHONE_NO,DA_USER FROM DA_HK_MOBILE ORDER BY 1 DESC ";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataTable finaldata = this.GenerateMOBILE_HK();
conn.Open();
da1.Fill(finaldata);
this._datasetHKMOBILE = new DataSet();
this._datasetHKMOBILE.Tables.Add(finaldata);
conn.Close();
da1.Dispose();
}
}
private DataTable GenerateDataTable()
{
DataTable table = new DataTable();
table.Columns.Add("BS_ID", typeof(string));
table.Columns.Add("BS_NAME_CHT", typeof(string));
table.Columns.Add("BS_NAME_ENG", typeof(string));
table.Columns.Add("BS_DEPT", typeof(string));
return table;
}
private DataTable GenerateTable()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_ITNL_HK_TEL", typeof(string));
return table;
}
private DataTable GenerateMOBILE_HK()
{
DataTable table = new DataTable();
table.Columns.Add("DA_USER", typeof(string));
table.Columns.Add("DA_PHONE_NO", typeof(string));
return table;
}
private void ShowData()
{
Viewtable();
GridView1.DataSource = this._dataSet;
GridView1.DataBind();
ViewItnlHKTel();
ADD_HK_TEL.DataSource = this._dataSetHKTEL;
ADD_HK_TEL.DataBind();
ViewITNLHKMOBILE();
ADD_HK_MOBILE.DataSource = this._datasetHKMOBILE;
ADD_HK_MOBILE.DataBind();
}
protected void lbladd_Click(object sender, EventArgs e)
{
//TextBox id = GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox;
////string strBS_ID = (GridView1.FooterRow.FindControl("BS_ID_tb") as TextBox).Text;
//DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
////string strBS_ID = BS_ID_tb.Text;
////string strBS_NAME_CHT = BS_NAME_CHT_tb.Text;
////string strBS_NAME_ENG = BS_NAME_ENG.Text;
//string strBS_DEPT = DEPT_ddl.SelectedItem.Value;
////using (SqlConnection conn = new SqlConnection(this._connectionString))
////{
//// string query = "INSERT INTO BS_USER(BS_ID , BS_NAME_CHT , BS_NAME_ENG , BS_DEPT) VALUES (#BS_ID , #BS_NAME_CHT , #BS_NAME_ENG , #BS_DEPT)";
//// SqlCommand cmd = new SqlCommand(query, conn);
//// cmd.Parameters.Clear();
//// cmd.Parameters.AddWithValue("#BS_ID", strBS_ID);
//// cmd.Parameters.AddWithValue("#BS_NAME_CHT", strBS_NAME_CHT);
//// cmd.Parameters.AddWithValue("#BS_NAME_ENG", strBS_NAME_ENG);
//// cmd.Parameters.AddWithValue("#BS_DEPT", strBS_DEPT);
//// conn.Open();
//// cmd.ExecuteReader();
//// conn.Close();
//// //Response.Redirect("");
////}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = true;
lblinsertuser.Visible = true;
lbCancelSave.Visible = true;
lbInsert.Visible = false;
}
protected void lbCancelSave_Click(object sender, EventArgs e)
{
GridView1.FooterRow.Visible = false;
lbInsert.Visible = true;
}
DataTable Selectindex()
{
DataTable dt = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT '請選擇部門' AS BS_NAME , '000' AS BS_ID UNION SELECT BS_NAME , BS_ID FROM BS_DEPT ORDER BY BS_ID ASC", conn))
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
}
}
}
catch (SqlException exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
catch (Exception exc)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + exc.Message + "');", true);
}
finally
{
}
return dt;
}
protected void OnDataBound(object sender, EventArgs e)
{
DropDownList DEPT_ddl = GridView1.FooterRow.FindControl("DropDownList1") as DropDownList;
DEPT_ddl.DataSource = Selectindex();
DEPT_ddl.DataTextField = "BS_NAME";
DEPT_ddl.DataValueField = "BS_ID";
DEPT_ddl.DataBind();
}
protected void lbSave_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert",StringComparison.OrdinalIgnoreCase))
{
GridView GridView1= (GridView)sender;
TextBox BS_ID_tb = (TextBox)GridView1.FooterRow.FindControl("BS_ID_tb");
string str_BS_ID = BS_ID_tb.Text;
TextBox BS_NAME_CHT_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_CHT_tb");
string str_BS_NAME_CHT = BS_NAME_CHT_tb.Text;
TextBox BS_NAME_ENG_tb = (TextBox)GridView1.FooterRow.FindControl("BS_NAME_ENG_tb");
string str_BS_NAME_ENG_tb = BS_NAME_ENG_tb.Text;
DropDownList DEPT_ddl = (DropDownList)GridView1.FooterRow.FindControl("DropDownList1");
string str_DEPT_value = DEPT_ddl.SelectedItem.Value;
InsertData(str_BS_ID, str_BS_NAME_CHT, str_BS_NAME_ENG_tb, str_DEPT_value);
GridView1.ShowFooter = false;
ShowData();
GridView1.FooterRow.Visible = false;
lblinsertuser.Visible = false;
lbCancelSave.Visible = false;
}
}
private void InsertData(string BS_ID, string BS_NAME_CHT, string BS_NAME_ENG, string BS_DEPT)
{
using (SqlConnection conn = new SqlConnection(this._connectionString))
{
conn.Open();
string sql = String.Format("Insert into BS_USER VALUES('{0}','{1}','{2}','{3}')", BS_ID, BS_NAME_CHT, BS_NAME_ENG, BS_DEPT);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
}
}
View state's purpose is simple:
it's there to persist state across postbacks.
That's why you are getting the initial values like empty strings in the gridview. Setting the property EnableViewState="false" force to get the data by rebinding the control, not from the viewstate. To understand view state more, see here.
I have 3 dropdownlist: select year, select make, select model. Upon select model the results should appear in a gridview. My tables are:
Makes with [(pk)MakeID, MakeName]; Models with [(pk)ModelID, Make_ID, ModelYear, ModelName]; and Wipers with [(pk)WiperID, Model_ID, Description, Emplacement, Price]. When I step through debug, I see 6 counts of records found, but I do not see it in gridview
I've looked at these for help, but no answers
ASP.net DropDownList populates GridView
Binding gridview with arraylist asp.net/c#
My Default.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="wrapper" align="center">
<asp:DropDownList ID="ddlYear" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Year_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlMake" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Make_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="Get_Wipers_By_Model">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="grdWiperList" runat="server">
</asp:GridView>
</form>
My Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Year drop down list is populated on page load
string query = "SELECT DISTINCT ModelYear FROM Models";
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddlYear.DataSource = cmd.ExecuteReader();
ddlYear.DataValueField = "ModelYear";
ddlYear.DataBind();
conn.Close();
}
}
ddlYear.Items.Insert(0, new ListItem("Select Year", "0"));
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void Year_Changed(object sender, EventArgs e)
{
//the Makes drop down list is populated on OnSelectedIndexChange event of the Year_Changed event
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Clear();
ddlModel.Items.Clear();
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearId = int.Parse(ddlYear.SelectedItem.Value);
if (yearId > 0)
{
string query = string.Format("SELECT DISTINCT MakeID, MakeName FROM Makes JOIN Models ON Make_ID = MakeID WHERE ModelYear = {0}", yearId);
BindDropDownList(ddlMake, query, "MakeName", "MakeID", "Select Make");
ddlMake.Enabled = true;
}
}
protected void Make_Changed(object sender, EventArgs e)
{
ddlModel.Enabled = false;
ddlModel.Items.Clear();
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearID = int.Parse(ddlYear.SelectedItem.Value);
int makeId = int.Parse(ddlMake.SelectedItem.Value);
if (makeId > 0)
{
string query = string.Format("SELECT ModelID, ModelName FROM Models WHERE ModelYear = {0} AND Make_ID = {1}", yearID, makeId);
BindDropDownList(ddlModel, query, "ModelName", "ModelID", "Select Model");
ddlModel.Enabled = true;
}
}
protected void Get_Wipers_By_Model(object sender, EventArgs e)
{
grdWiperList.DataSource = Connection.GetWipersByModel
(!IsPostBack ? "%" : ddlModel.SelectedValue);
grdWiperList.DataBind();
}
}
My Connection.cs
public static ArrayList GetWipersByModel(string modelType)
{
ArrayList listResults = new ArrayList();
string query = string.Format
("SELECT * FROM Wipers WHERE Model_ID LIKE '{0}'", modelType);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int wiperID = reader.GetInt32(0);
int model_id = reader.GetInt32(1);
string description = reader.GetString(2);
string itemNo = reader.GetString(3);
string emplacement = reader.GetString(4);
decimal price = reader.GetDecimal(5);
Wipers wipers = new Wipers(wiperID, model_id, description, itemNo, emplacement, price);
listResults.Add(wipers);
}
}
finally
{
conn.Close();
}
return listResults;
}
I think this because the updatePanel control try to add trigger between UpdatePanel control and DropDownList Control
I want partial postback(asyncpostback) instead fullpostback.but it's not working. Dynamically created checkbox where check or unchecked checkbox cause fullpostback
but it should be asyncpostback.Here is my code.....
<asp:CheckBoxList ID="chkList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="chkList_SelectedIndexChanged"
ClientIDMode="AutoID">
</asp:CheckBoxList>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" Visible="false"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chkList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
C# code:
private static readonly string constring = ConfigurationManager.ConnectionStrings["ConnectionStrRead"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand com = new SqlCommand("Select * from Category");
com.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
int dtRows = dt.Rows.Count;
List<string> itemList = new List<string>();
for (int i = 0; i < dtRows; i++)
{
//itemList = new List<string>();
string item = dt.Rows[i]["CategoryName"].ToString() + "(" + dt.Rows[i]["CreateUser"].ToString() + ")";
itemList.Add(item);
}
chkList.DataSource = itemList.ToArray();
chkList.DataBind();
con.Close();
}
}
protected void chkList_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = true;
lblMessage.Text = string.Empty;
foreach (ListItem item in chkList.Items)
{
if (item.Selected)
{
lblMessage.Text += item.Text + "<br/>";
}
}
}
Can u check your scriptmanager EnablePartialRendering attribute. It must be EnablePartialRendering="true"
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableViewState="False" EnablePartialRendering="true" EnableScriptGlobalization="true" > </asp:ScriptManager>
If problem is not about that u can try add AsyncPostBackTrigger in code behind
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(chkList);
I am using a GridView and in it I have four columns: labelID, fName, lName and Grade. The Grade is a simple Pass or Fail Radiobuttonlist. Once the data is updated I would like it to pull the data on the next reload to show the selected value if the user has passed or failed. Here is the code:
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButtonList ID="rblChoices" runat="server" OnSelectedIndexChanged="rblChoices_SelectedIndexChanged" Text='<%# Eval("Grade") %>'>
<asp:ListItem Value="Pass" Text="Pass"></asp:ListItem>
<asp:ListItem Value="Fail" Text="Fail"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=LiquorStore;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT id, firstname, lastname, nickname, Grade FROM Company", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
}
Thank you in advance!
You have to use the GridView RowDataBound event for this
HTML
<asp:GridView runat="server" ID="gvUsers" OnRowDataBound="gvUsers_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButtonList ID="rblChoices" runat="server">
<asp:ListItem Value="Pass" Text="Pass"></asp:ListItem>
<asp:ListItem Value="Fail" Text="Fail"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
C# Code
A very simple company class - Company.cs
public class Company
{
public string Name { get; set; }
public string Grade { get; set; }
}
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
List<Company> companies = new List<Company>()
{
new Company(){ Name = "Toyota", Grade = "Pass"},
new Company(){ Name = "Form", Grade = "Fail"}
};
gvUsers.DataSource = companies;
gvUsers.DataBind();
}
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
string grade = DataBinder.Eval(e.Row.DataItem, "Grade") as string;
if (!string.IsNullOrEmpty(grade))
{
RadioButtonList radio = e.Row.FindControl("rblChoices") as RadioButtonList;
radio.Items.FindByValue(grade).Selected = true;
//You can use this to select as well - see comments from Andomar
//radio.SelectedValue = grade;
}
}
}
}
OUTPUT