How to add Item in Dropdown list in cs file - c#

This is my CS file for dropdown:
protected void BindDropDownList()
{
DataTable dt = new DataTable();
string connString = System.Configuration.ConfigurationManager.AppSettings["EyeProject"];
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
string sqlStatement = "SELECT FirstName FROM tbl_UserDetails";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource =dt;
DropDownList1.DataTextField = "FirstName"; // the items to be displayed in the list items
DropDownList1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "No Data Found To display in the DropDown List";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
By using this one iam getting values of table Firstname values now i want to add one more item Called ALLrecords.
How can i add it.
this is my Aspx file
<div class="label">
Select Name:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</div>

Try this
DropDownList1.Items.Add(new ListItem("All Record"));
and if you want to add item with value then
DropDownList1.Items.Add(new ListItem("All Record","0"));
//or if you want to add at particular index then
DropDownList1.Items.Insert(0,new ListItem("All Record"));// 0 is index of item
hope this helps.

insert an item at specified index
DropDownListID.Items.Insert(0, new ListItem("Default text", "Default value")

DropDownList1.Items.Insert(0,new ListItem("AllRecords","itsValue_on_dropdownlist")); // use 0 to show "ALLRecords" text on top in dropdownlist
i would suggest that you should bind values to dropdownlist also.
like this -
DropDownList1.DataValueField = "FirstName";

First write onLoad with "addItems" function in dropdownlist declaring tag .aspx file like this:
then create "addItems" function in cs file.
<asp:DropDownList ID="DropDownList1" runat="server" OnLoad="addDeleteItems" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
protected void addItems(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ListItem newItem = new ListItem("rose", "i");
ddl.Items.Add(newItem);
}

Related

Filling the default value of a dropdown in a gridview with the current value

After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}

ASP.NET C# Creating checkboxes from DataTable

I am new to ASP.NET, but I need to create checkboxes from a query result. So far here is what I have.
In my code behind...I pull the query that I need and then create a DataTable from that result like so:
DataTable dtLocations = new DataTable();
dtLocations.Columns.Add("ID");
dtLocations.Columns.Add("VALUE");
// Pull locations and add to our datatable
string strConnection = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (SqlConnection dbConn = new SqlConnection(strConnection))
{
SqlDataAdapter dbAdapter = new SqlDataAdapter();
SqlCommand dbCommand = new SqlCommand();
dbConn.Open();
dbCommand.CommandText = #"SELECT location_id, location_desc FROM admin_locations WHERE enabled = 'Y'";
dbCommand.Connection = dbConn;
SqlDataReader dbReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dbReader.HasRows) {
while (dbReader.Read()) {
dtLocations.Rows.Add(new object[] { dbReader["location_id"].ToString(), dbReader["location_desc"].ToString() });
}
}
}
return dtLocations;
I then have a class level var defined as
public DataTable dtLocations = new DataTable();
which I populate using the method above in my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
dtLocations = createLocationsDataTable();
}
}
Then in my aspx file (not code behind) I'm doing this to try and create the checkboxes, which needless to say, does not work.
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:CheckBox ID="idLocationChk" runat="server" Value="<% Response.Write(row["ID"].ToString()); %>" />
<% } %>
Can someone show me how you're supposed to do this in ASP.NET c#? I'll also need to be able to get the value of any that are checked in my code behind when a button on the page is clicked.
When I try using a CheckBoxList like this it tells me I can not use codeblocks here.
<asp:CheckBoxList ID="message_locations" runat="server">
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:ListItem>TEST</asp:ListItem>
<% } %>
</asp:CheckBoxList>
You can bind a DataTable directly to a CheckBoxList
if (!IsPostBack)
{
CheckBoxList1.DataSource = dtLocations;
CheckBoxList1.DataTextField = "location_desc";
CheckBoxList1.DataValueField = "location_id";
CheckBoxList1.DataBind();
}

asp.net c# send ArrayList to gridview not displaying items

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

Error in Dropdown "SelectedIndexChanged" event, while Seleting new item from RadComboBox

In my webpage, there is a RadComboBox outside the RadGrid and a Dropdown inside RadGrid.
Data inside Dropdown is bind based on RadComboBox item selection.
Ex: If from RadComboBox, item "Company" is selected, then data inside Dropdown will be related to "Company" (i.e, Company1, Company2,company3, etc)
HTML code:
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false" Filter="StartsWith" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true" DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server">
<Columns>
<telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
C# Code:
public DataSet GetCompanyNames()
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("General.usp_tbl_BuyerCode_Query", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
da.Fill(ds);
con.Close();
}
catch (Exception ex)
{
}
return ds;
}
protected void BindComapnyDL()
{
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Code";
ddlCompany.DataSource = GetCompanyNames();
ddlCompany.DataBind();
Session["Comp"] = ddlCompany.SelectedValue.ToString();
}
protected void ddlCompany_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (ddlCompany.SelectedItem != null)
{
SqlConnection con = new SqlConnection(strcon);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCodeID],[AccountCode]+' - '+[AccountDescription] as[AccountDescription] FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK) Where [CompanyCode] = '" + Session["Comp"] + "' order by [AccountCode]+' - '+[AccountDescription]", con);
con.Open();
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
list.DataTextField = "AccountDescription";
list.DataValueField = "AccountCodeID";
list.DataSource = dt;
list.DataBind();
}
else
{
Response.Write("Please select Company first");
}
}
Now, when I try to change the company using "ddlCompany_SelectedIndexChanged" event,
I get below error:
System.NullReferenceException: Object reference not set to an instance of an object.
at line :
list.DataTextField = "AccountDescription";
Please suggest what is wrong in my code. Thanks in advance
This line contains error dropdown is not properly find
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
Where did You placed Dropdown inside any control..??
visite this link http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/how-to/operations-with-ms-dropdownlist-in-edititemtemplate-of-gridtemplatecolumn
try this
foreach (GridDataItem item in RGGSTAcCode.EditItems)
{
DropDownList list = item.FindControl("ddlAcCode") as DropDownList;
//Now we can do stuff with the "list"
}
Keep in mind that the row needs to be in Edit Mode to find controls in its EditItemTemplate.

Possible to fill SqlDataSource with SqlDataAdapter?

I currently have this code to populate ASP.NET gridview from code behind with DataTable.
protected void bindGridView()
{
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstr"].ConnectionString);
SqlCommand cmd = sqlConn.CreateCommand();
cmd.CommandText = "SELECT id AS 'Member ID', name AS Name, age AS Age, sympton AS Sympton, phone AS Phone, nirc AS NIRC, address AS Address FROM tbl_customer_profile WHERE id = #id";
cmd.Parameters.AddWithValue("#id", txtSearchID.Text);
DataTable dtSearchResult = new DataTable();
SqlDataAdapter daSearchResult = new SqlDataAdapter();
try
{
sqlConn.Open();
daSearchResult.SelectCommand = cmd;
daSearchResult.Fill(dtSearchResult);
gridSearchResult.DataSource = dtSearchResult;
gridSearchResult.DataBind();
}
catch (SqlException ex)
{
lblStatus.Text = ex.Message;
}
finally
{
sqlConn.Close();
}
}
But I would lose the Grid's Selection, Sorting, Paging functions. So I was thinking if I could fill to SqlDataSource instead of Datatable and then bind to Gridview, I wouldn't have to handle the selection, sorting etc manually?
But I can't just simply do like daSearchResult.Fill(sqlDataSource1);
Is there any workaround?
Kind of like what Neeraj was saying you can bind directly to a gridview with an SqlDataSource.
You don't need to have all that plumbing code.
This is how in asp.net
<asp:GridView ID="grid" runat="server" DataSourceID="source"></asp:GridView>
<asp:SqlDataSource ID="source" runat="server"></asp:SqlDataSource>
This is how in C#
SqlDataSource source =new SqlDataSource();
GridView grid = new GridView();
grid.DataSource = s;
grid.DataBind();

Categories

Resources