Radio button list selected value not persistent in asp.net - c#

I have two dynamically populated radio button lists. The first one gets populated on a button click, the other one on the change event of the first radio button list. The problem is only with the second list. The issue is that I am not able to retrieve the changed value of the second radio button list in the InsertButton_Click method(marked by **). It always returns the default index value i.e 0. I don't have anything in page_load event. I read quite a few similar questions but none seem to help. Please guide. Below is the asp and c# code for the same:
ASP:
<asp:Button id="SaveButton"
Text="Save"
runat="server" onclick="SaveButton_Click">
</asp:Button>
<asp:Button id="VisualiseButton"
Text="Visualise"
runat="server" onclick="VisualiseButton_Click">
</asp:Button>
<!--<hr />-->
<asp:RadioButtonList id="RadioButtonList2" runat="server" Visible="false"
onselectedindexchanged="RadioButtonList2_SelectedIndexChanged" ></asp:RadioButtonList>
<asp:RadioButtonList id="RadioButtonList1" runat="server" Visible="false" ></asp:RadioButtonList>
<asp:Button id="SaveToDBButton"
Text="Insert"
runat="server" Visible="false" onclick="InsertButton_Click">
C#:
protected void SaveButton_Click(object sender, EventArgs e)
{
String selQuery = "SELECT id, name FROM categories";
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(selQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
RadioButtonList2.DataSource = dt;
RadioButtonList2.DataTextField = "name";
RadioButtonList2.DataValueField = "id";
RadioButtonList2.DataBind();
RadioButtonList2.RepeatColumns = 3;
RadioButtonList2.AutoPostBack = true;
RadioButtonList2.Visible = true;
}
catch (SqlException ex)
{
}
finally
{
if (con != null)
{
con.Close();
}
}
}
protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
{
String catId = RadioButtonList2.SelectedValue;
SqlCommand cmdselect = new SqlCommand("SELECT DISTINCT categoryId, linkTablesCategories.tableName, tableDescription FROM linkTablesCategories, tableDescriptions where linkTablesCategories.tableName = tableDescriptions.tableName and categoryId ='" + catId + "'");
RadioButtonList1.Items.Clear();
try
{
con.Open();
cmdselect.Connection = con;
SqlDataReader dar = cmdselect.ExecuteReader();
if (dar.HasRows)
{
while (dar.Read())
{
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
li.Attributes.Add("title", dar["tableDescription"].ToString());
RadioButtonList1.Items.Add(li);
}
}
RadioButtonList1.Visible = true;
SaveToDBButton.Visible = true;
}
catch (SqlException ex)
{
//lblMessage.Text = ex.Message;
}
finally
{
cmdselect.Dispose();
if (con != null)
{
con.Close();
}
}
}
protected void InsertButton_Click(object sender, EventArgs e)
{
String tableId="";
**tableId = RadioButtonList1.SelectedItem.Text;**
String path = Server.MapPath("~/");
string filepath = path + Session["filepath"].ToString();
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tableId;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();
}

it was with the line:
ListItem li = new ListItem(dar["tableName"].ToString(), dar["categoryId"].ToString());
The categoryId was a constant value and thus the issue, again my bad.
Thanks

Related

dynamically add itemplate to the gridview

I have created gridview. Added a textbox to specify what number of columns user want to add to the grid dynamically and its done successfully.
I want to add text box to the dynamically added fields to enter the data and save it to the database(I am able to add text fields to the rows and save data) but i didnt got any solution yet.
I have tried with itemplate but I don't know much about it. i have added my code below.
Here is my aspx code
<input type="hidden" runat="server" value="0" id="columnAdded"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:TemplateField HeaderText="S. No.">
<ItemTemplate>
<asp:Label ID="lblsno" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Parts" DataField="parts">
</asp:BoundField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
and here is .cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
drpstation.Items.Clear();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "stationdesc");
drpstation.DataSource = ds.Tables[0];
drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
drpstation.DataBind();
drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
}
catch (Exception ex)
{
string Msg = "select station error";
Msg += ex.Message;
}
finally
{
con.Close();
}
}
if (!IsPostBack)
{
griddisplay();
}
}
public void griddisplay()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
//DataTable dt = new DataTable();
//dt.Columns.Add("Parts", typeof(string));
//DataRow drr = dt.NewRow();
//drr["Parts"] = "Weldmet";
//dt.Rows.Add(drr);
//drr = dt.NewRow();
//drr["Parts"] = "MFG Parts";
//dt.Rows.Add(drr);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
catch (Exception d)
{
string message = "grid error";
message += d.Message;
}
finally
{
con.Close();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
GridView1.Columns.Add(test);
TextBox txtname = new TextBox();
string txtunit = "txtunit";
txtname.ID = txtunit + i;
}
griddisplay();
columnAdded.Value = (addedColumn + num).ToString();
}
public class TemplateHandler : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
TextBox txtbox = new TextBox();
txtbox.Text = "test";
txtbox.DataBinding += Txtbox_Binding;
container.Controls.Add(txtbox);
}
private void Txtbox_Binding(object sender, EventArgs e)
{
//throw new NotImplementedException();
TextBox txttest = (TextBox)sender;
GridViewRow container = (GridViewRow)txttest.NamingContainer;
//txttest.Text = ((TableNameClass)container.DataItem).SkillText;
((DataRowView)container.DataItem)["SkillText"].ToString();
}
}
Please help
Just a pseudo/sample code(not tested!) based on the code you posted, to give you some heads-up
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
GridView1.Columns.Add(test);
// ... Other code as you need
}
}
Hope this help you.

how to get column data when check box is checked using data list in asp.net

this is eswar.k , i have one problem in asp.net..that is ..
i have one datalist .that is shows data from database ..that is contains .check box,image,and lables..here what is the problem .. when i am checked on check box ,i have to display the email labels into the text box..(like multiple recipients eg:eswar#gmil.com,eee#yahoo.in..etc )
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strconnstring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
string strquery = "select chid,chname,chlanguage,chrating,chemail,contenttype,data from tbl_channel_join Order by chid";
SqlCommand cmd = new SqlCommand(strquery);
SqlConnection con = new SqlConnection(strconnstring);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
//GridView1.DataSource = dt;
//GridView1.DataBind();
//GridView2.DataSource = dt;
//GridView2.DataBind();
dl_channels.DataSource = dt;
dl_channels.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
Let's say you have a Gridview with checkbox like this :
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkIT" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:Button ID="btnDisplay" runat="server" Text="Show data selected" OnClick="btnDisplay_Click"/>
<asp:TextBox id="textboxDataDisplay" runat="server" />
with a button to show the selected checkbox columns
C# code
protected void btnDisplay_Click(object sender, EventArgs e)
{
string data = "";
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkCtrl") as CheckBox);
if (chkRow.Checked)
{
string yourFirstRowCell = row.Cells[1].Text;
string yourSecondRowCell = row.Cells[2].Text;
string yourThirdRowCell = row.Cells[3].Text;
data = yourFirstRowCell + yourSecondRowCell + yourThirdRowCell;
}
}
}
textboxDataDisplay.text = data;
}
Row cells are the cells in that row you want to get where the checkbox is checked.

How to Bind column of a table in array and display result one by one on button click event?

I have created method to store column value of Questions from Question table into array and now I wanted to display in a label one by one on button click event.
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
con = new SqlConnection(str);
cmd = new SqlCommand("select Question from Questions", con);
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
list.Add(dtrow);
}
return list;
}
Try this....
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandArgument="0" />//dEFINATION OF BUTTON ON ASPX PAGE
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list=BindDataToArray();
int I=( Convert.ToInt32(Button1.CommandArgument));
if (I < list.Count)
{
Label1.Text = list[I] as string; //Label in which u want to show message
Button1.CommandArgument = (I + 1).ToString();
}
else
{
Label1.Text = "eND OF LIST";
Button1.Enabled = false;
}
}
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
con = new SqlConnection(str);
cmd = new SqlCommand("select Question from Questions", con);
con.Open();
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
list.Add(dtrow["Question"].ToString());
}
return list;
}
Save the list in to the session
initialize a int with value = 0 and store this also in the session.
when the button is clicked
get the list and int from the session
update the label with the list[index] value where index is the int.
increment the int by one and resave it in the session.
It seems that you are looking for gridview control of asp.net.
Example http://www.dotnetfunda.com/articles/article1594-how-to-populate-gridview-from-code-behind.aspx
// in Aspx Page
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
CommandArgument="1" /><asp:Label
ID="Label1" runat="server" Text="Label"></asp:Label>
//in Aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list = BindDataToArray();
int I = (Convert.ToInt32(Button1.CommandArgument.Count()));
//int I = (Convert.ToInt32(Button1.CommandArgument));
if (I < list.Count)
{
Label1.Text = list[I] as string; //Label in which u want to show message
Button1.CommandArgument = (I + 1).ToString();
}
else
{
Label1.Text = "eND OF LIST";
Button1.Enabled = false;
}
}
public ArrayList BindDataToArray()
{
ArrayList list = new ArrayList();
DataTable dt = new DataTable();
//con = new SqlConnection(con);
SqlCommand cmd = new SqlCommand("SELECT SurveyName FROM tblSurveyName", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
foreach (DataRow dtrow in dt.Rows) { list.Add(dtrow["SurveyName"].ToString()); }
return list;
}

issue with populating dropdownlist in gridview edit mode in c#

I am having editable Gridview with column named Country which has so long listing.
When I am showing data the value of Country is in Label but when I choose edit should show DropDownList with country listings. I am able to show listings. it should show the country selected as that was in label.
I have tried with this but dropdownlist is filled with System.Row.DataRowView also it is not set at SelectedValue given as cvalue
aspx page
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#Bind("Country")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px"
Width="194px">
<asp:ListItem Value="-1">Select..</asp:ListItem>
<asp:ListItem Value="af">Afghanistan</asp:ListItem>
<asp:ListItem Value="ax">Aland Islands</asp:ListItem>
<asp:ListItem Value="al">Albania</asp:ListItem>
</asp:DropDownList>
<EditItemTemplate>
.cs file
void gvhoteldetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
string cnm="",cvalue="";
string getCountry = "Select * from tbl_countrynames where `Name`='" + cname + "'";
string getCountrynames = "Select * from tbl_countrynames";
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd1 = new MySqlCommand(getCountrynames, con);
DataSet ds1 = new DataSet();
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd1);
da1.Fill(ds1);
MySqlCommand cmd = new MySqlCommand(getCountry, con);
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
cnm = ds.Tables[0].Rows[0]["Name"].ToString();
cvalue = ds.Tables[0].Rows[0]["Value"].ToString();
}
DropDownList ddlcountry = (DropDownList)e.Row.FindControl("ddlCCountry");
ddlcountry.DataSource = ds1;
ddlcountry.SelectedValue = cvalue;
ddlcountry.DataBind();
}
What could be wrong?
This worked for me. When populating the GridView, you should populate each DropDownList in the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
numberFormatDA formatDA = new numberFormatDA();
DataTable mytable = new DataTable();
DataColumn formatIDcolumn = new DataColumn("fkNumberFormat");
DataColumn formatNameColumn = new DataColumn("numberFormat");
mytable.Columns.Add(formatIDcolumn);
mytable.Columns.Add(formatNameColumn);
DataSet ds = new DataSet();
ds = formatDA.getNumberFormatsDS();
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox txtSite = (TextBox)e.Row.FindControl("txtIDSite");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlNumberFormat");
DataRow[] rows = ds.Tables[0].Select();
foreach (DataRow row in rows)
{
DataRow newrow = mytable.NewRow();
newrow["fkNumberFormat"] = row["idnumberFormat"];
newrow["numberFormat"] = row["numberFormat"];
mytable.Rows.Add(newrow);
}
ddl.DataSource = mytable;
ddl.DataTextField = "numberFormat";
ddl.DataValueField = "fkNumberFormat";
int numberFormatID = 0;
Label lblFormatID = (Label)e.Row.FindControl("numberFormatLabel");
numberFormatID = Int32.Parse(lblFormatID.Text);
ddl.SelectedValue = numberFormatID.ToString();
ddl.DataBind();
}
}
Hope this helps!
This way you can make it work but I know there's a much better way to achieve this..
Try this for now...
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow gvr = GridView1.Rows[e.NewEditIndex];
Label lb = (Label)gvr.FindControl("lblCountry");
GridView1.EditIndex = e.NewEditIndex;
binddata();
getselected(lb.Text);
}
private void getselected(string text)
{
GridViewRow gvr = GridView1.Rows[GridView1.EditIndex];
DropDownList dr = (DropDownList)gvr.FindControl("ddlCCountry");
dr.SelectedIndex = dr.Items.IndexOf(dr.Items.FindByText(text));
}
protected void gvGeneralMaster_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
if (clsGeneral._strRights[2] == "0")
{
//ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
Response.Redirect("UnauthorizedUser.aspx");
}
else
{
GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.NewEditIndex];
ViewState["COUNTRY"] = ((Label)gvRow.FindControl("lblCountry")).Text.Trim();
ViewState["STATE"] = ((Label)gvRow.FindControl("lblState")).Text.Trim();
gvGeneralMaster.EditIndex = e.NewEditIndex;
GetGeneralDetails();
}
}
catch (Exception ex)
{
lblErrorMsg.Text = ex.Message.ToString();
if (!ex.Message.ToString().Contains("Thread was being aborted."))
{
//oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
}
}
}
protected void gvGeneralMaster_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
if (clsGeneral._strRights[2] == "0")
{
//ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
Response.Redirect("UnauthorizedUser.aspx");
}
else
{
GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.RowIndex];
oPRP._GeneralCode = int.Parse(((Label)gvRow.FindControl("lblEGenCode")).Text.Trim());
oPRP._GenaralName = ((TextBox)gvRow.FindControl("txtECity")).Text.Trim();
oPRP._StateName = ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() : "";
oPRP._CountryName = ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() : "";
oPRP._Remarks = ((TextBox)gvRow.FindControl("txtERemarks")).Text.Trim();
oPRP._Active = ((CheckBox)gvRow.FindControl("chkEditActive")).Checked;
oPRP._ModifiedBy = Session["CurrentUser"].ToString();
oDAL.SaveUpdateGeneralMaster("UPDATE", oPRP);
gvGeneralMaster.EditIndex = -1;
GetGeneralDetails();
}
}
catch (Exception ex)
{
lblErrorMsg.Text = ex.Message.ToString();
if (!ex.Message.ToString().Contains("Thread was being aborted."))
{
//oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
}
}
}
It's too late for the answer, but hope it would help someone. You can place the SelectedValue property inside your dropdownlist tag like below:
<asp:DropDownList SelectedValue='<% Eval("Country") %>' ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px" Width="194px">
<asp:ListItem Value="-1">Select..</asp:ListItem>
<asp:ListItem Value="af">Afghanistan</asp:ListItem>
<asp:ListItem Value="ax">Aland Islands</asp:ListItem>
<asp:ListItem Value="al">Albania</asp:ListItem>
</asp:DropDownList>

how to fill DropDownList from database in asp.net?

how to fill DropDownList from database in asp.net ?
and when i pick value from the DropDownList how to catch this event ?
Conn.Open();
SQL = "SELECT distinct city FROM MEN";
dsView = new DataSet();
adp = new SqlDataAdapter(SQL, Conn);
adp.Fill(dsView, "MEN");
adp.Dispose();
DropDownList1. ?????? (what do to ?)
thanks in advance
You set the DataSource, DataTextField and DataValueField and call DataBind() in order to populate the dropdownlist.
The datasource can be pretty much any IEnumerable and the text and value will be looked up with reflection.
The event you want to catch is the SelectedIndexChanged event - this will fire when you change the selection.
First take the details in a dataset
then the following code will help you:
DropDownList1.DataSource = ds
DropDownList1.DataTextField = "emailid"
DropDownList1.DataValueField = "userid"
DropDownList1.DataBind()
DropDownList1.Items.Insert(0, New ListItem("select", "-1"))
Simple sample code :
DropDownList.DataSource = yourDataSource;
DropDownList.DataTextField = "displayNameColumnName ";
DropDownList.DataValueField = "TheValueColumnName";
DropDownList.DataBind();
This could be a complete walkthrough for you in this case :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownLists();
}
}
protected void Page_Init(object sender, EventArgs e)
{
SqlDataSource sqlDS = new SqlDataSource();
sqlDS.ConnectionString = ConfigurationManager.ConnectionStrings[0].ToString();
sqlDS.SelectCommand = "select GenderID,Gender from mylookupGender";
form1.Controls.Add(sqlDS);
DropDownList ddl = new DropDownList();
ddl.ID = "dddlGender";
ddl.DataSource = sqlDS;
ddl.DataTextField = "Gender";
ddl.DataValueField = "GenderID";
form1.Controls.Add(ddl);
// ... Repeat above code 9 times or put in a for loop if they're all the same...
}
private void BindDropDownLists()
{
foreach (Control ctl in form1.Controls)
{
if (ctl is DropDownList)
{
(ctl as DropDownList).DataBind();
}
}
}
//...Wrote separate class for calling this function
FunctionClass obj = new FunctionClass();
List<Designation> details = new List<Designation>();
bool result1 = obj.DataDrop(out details);
if (result1 == true)
{
dropDownDesignation.DataSource = details;
dropDownDesignation.DataTextField = "designation";
dropDownDesignation.DataValueField = "Designation_ID";
dropDownDesignation.DataBind();
dropDownDesignation.Items.Insert(0, new ListItem("--Select--", "0"));
}
//..This function wrote inside FunctionClass and called from aspx.cs page
public bool DataDrop(out List<Designation> designationDetails)
{
designationDetails = new List<Designation>();
conn = new SqlConnection(connectionName);
conn.Open();
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "DesignationDetails";
userReader = command.ExecuteReader();
if(userReader.HasRows)
{
while(userReader.Read())
{
designationDetails.Add(new Designation()
{
designationId=userReader.GetInt32(0),
designation=userReader.GetString(1)
});
}
}
return true;
}
//..This should declare outside the class but inside the namespace
public class Designation
{
public int designationId { get; set; }
public string designation { get; set; }
}
Another way to bind dropdownlist is...
<asp:DropDownList ID="ddlCity" runat="server" DataValueField="pkId" DataTextField="cityName" DataSourceID="sqlDB">
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDB" ConnectionString='$Name of connecitonstring' runat="server" SelectCommand="Select * from tbl_City"></asp:SqlDataSource>

Categories