values not show in dropdownlist - c#

i try to add values in dropdownlist in gridview query works fine but it appears as this ..
gridview html
<asp:BoundField HeaderText="ApproveID" DataField="ApproveID" ></asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#
Eval("ApproveID") %>' Visible = "false" />
<asp:DropDownList ID="DropDownList4" runat="server"
class="vpb_dropdown">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("DropDownList4") as
DropDownList);
ddlCountries.DataSource = GetData("SELECT ApproveID,ApproveType FROM
ApproveType");
ddlCountries.DataTextField = "ApproveType";
ddlCountries.DataValueField = "ApproveID";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
//string country = (e.Row.FindControl("lblCountry") as Label).Text;
//ddlCountries.Items.FindByValue(country).Selected = true;
}
}
values are not inside in dropdownlist ..how to show values in dropdown??
and when i debug the code it cant show me any error
getdata code
private DataSet GetData(string query)
{
string conString =
ConfigurationManager.ConnectionStrings["mydms"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}

Set
DropDownList1.SelectedValue = "Some Value";
then you will get the value as default

Get data function returns null or empty value so it wont through error or exception while debugging.Your code working fine better check data in the database.

In a project I participated we returned the DataTable instead of DataSet and it was working fine with dropdowns. We had code like this:
if( ds.Tables.Count == 1)
return ds.Tables[0];
else
return new DataTable();
Besides I would change the way of databinding. In my opinion using ObjectDataSource is a better approach becuase the event is called only when the data is needed and you don't have to do checks like this:
if (e.Row.RowType == DataControlRowType.DataRow)

After your last comment you should check if the DataSet contains the record you want ot set as selected:
if (ddlCountries.Items.FindByValue(country) != null)
{
ddlCountries.Items.FindByValue(country).Selected = true;
}

Related

asp:gridview filter using listbox cannot make multiple selection

I have this asp:gridview in which I show data using mySql stored procedure. I have this listbox named ddlstatus which I use to filter the data. I use viewstate to show data that are selected from the listbox. The problem is I want to make multiple selection on this listbox and show data for each selection made on it, but when it only shows data for the initial selection.
The below is the client side code:
<asp:Label ID="lblstat" Text="status" Visible="false" runat="server"></asp:Label>
<asp:ListBox ID="ddlstatus" runat="server" OnSelectedIndexChanged="DropDownChange" AutoPostBack="true" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
<asp:GridView ID="gdvTM" runat="server" ControlStyle-Width="100%" AutoGenerateColumns="False" DataKeyNames="ID" OnRowDeleting="gdvTM_RowDeleting" PageSize="5" CssClass="cssgridview" AlternatingRowStyle-BackColor="#d5d8dc">
<Columns >
<asp:TemplateField HeaderText="Current Status">
<ItemTemplate >
<asp:Label ID="lblcstat" runat="server" Text='<%# Eval("status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The below is the server side code:
private void BindDropDownList()
{
PopulateDropDown(ddlstatus, lblstat.Text);
}
private void PopulateDropDown(ListBox ddl, string columnName)
{
ddl.Items.Clear();
ddl.DataSource = BindDropDown(columnName);
ddl.DataTextField = columnName;
ddl.DataValueField = columnName;
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("Please select", "0"));
}
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
int i = dt.Rows.Count;
gdvTM.DataBind();
this.BindDropDownList();
TableCell cell = gdvTM.HeaderRow.Cells[0];
setDropdownselectedItem(ViewState["stat"] != null ? (string)ViewState["stat"] : string.Empty, ddlstatus);
}
private void setDropdownselectedItem(string selectedvalue, ListBox ddl)
{
if (!string.IsNullOrEmpty(selectedvalue))
{
ddl.Items.FindByValue(selectedvalue).Selected = true;
}
}
protected void DropDownChange(object sender, EventArgs e)
{
ListBox dropdown = (ListBox)sender;
string selectedValue = dropdown.SelectedItem.Value;
switch (dropdown.ID.ToLower())
{
case "ddlstatus":
ViewState["stat"] = selectedValue;
break;
}
this.BindGrid();
}
private DataTable BindDropDown(string columnName)
{
string username = uName.Text;
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlCommand cmd = new MySqlCommand("SELECT DISTINCT (" + columnName + ") FROM approved WHERE tm = #tm AND " + columnName + " IS NOT NULL", con);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#tm", username);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Below is the MySql stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData`(in statusVal varchar(45))
BEGIN
SELECT *
FROM approved
WHERE (statusVal IS NULL
OR status = statusVal)
order by date desc;
END
How can I make this happen? Thanks in advance.
Please make listbox multiple
<asp:ListBox id="ListBox1"
Rows="6"
Width="100px"
**SelectionMode="Multiple"**
runat="server">
<asp:ListItem Selected="True">Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
Then in server side
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.Text = "You chose: <br />";
// Iterate through the Items collection of the ListBox and
// display the selected items.
foreach (ListItem item in ListBox1.Items)
{
if(item.Selected)
{
Message.Text += item.Text + "<br />";
}
}
}
First of all, auto post back not allow you to select multiple items because upto select second item, the postback already happens by first selected item so,
You have to set AutoPostBack="false" for your list box,
<asp:ListBox ID="ddlstatus" runat="server" AutoPostBack="false" AppendDataBoundItems="true" SelectionMode="Multiple"></asp:ListBox>
For collecting multiple selected items we simply choose button for instance, you can collect those items wherever you want,
Then add one button that will call below code
<asp:Button ID="button1" runat="server" OnClick="button1_Click" Text="Click"/>
On above button event handler add below code,
protected void button1_Click(object sender, EventArgs e)
{
var selectedNames = ddlstatus.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value)
.ToList();
string selectedValue = string.Join("','", selectedNames);
selectedValue = "'" + selectedValue + "'";
ViewState["stat"] = selectedValue;
}
Then the comma separated items in your ViewState will be used in your stored procedure parameter
string statusVal = null;
if (ViewState["stat"] != null && ViewState["stat"].ToString() != "0")
{
statusVal = ViewState["stat"].ToString();
}
cmd.Parameters.AddWithValue("statusVal", statusVal); //<= Now this string variable contains comma separated list box items values.
If you populate your list box on Page_Load then make sure that you should populate it into !Page.IsPostBack like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Populate your list box here
}
}
And your SP is
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetTMData1`(in statusVal varchar(255))
BEGIN
IF statusVal = '\'\'' THEN
select * from approved;
ELSE
SET #sql = CONCAT('SELECT * FROM approved WHERE status IN (', statusVal, ')');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF ;
END
If you select multiple items from the dropdown then your SP's parameter data look like '\'apple\',\'banana\''. If not then it look like '\''.
There's a few issues that I could spot that may need to be addressed,
Ensure that the method BindDropDownList is only called on a non postback (page refresh), because your method PopulateDropDown is clearing the items on the list which means that viewstate cannot be restored in a postback, hence the probable reason why only one item is being selected.
I'm not 100% of the table schema, but the SQL provided does not seem to be able to query by more than one status properly, you should probably send a comma separated list of values, and in SQL turn them into a temp table so that you effectively search for items with multiple status (you should probably create a new question for this).
Do not use SelectedItem for multiple selections, instead you need to iterate your list items for those that are selected, and you don't need to use ViewState to pass it along (you probably did because of point 1. above). For example you could replace your method BindGrid and DropDownChange with:
private void BindGrid()
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
MySqlDataAdapter sda = new MySqlDataAdapter();
MySqlCommand cmd = new MySqlCommand("GetTMData");
cmd.CommandType = CommandType.StoredProcedure;
string statusVal = null;
foreach (ListItem item in ddlstatus.Items)
{
if(item.Selected)
{
if(statusVal.length > 0)
statusVal += ",";
statusVal += item.Value;
}
}
cmd.Parameters.AddWithValue("statusVal", statusVal);
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
gdvTM.DataSource = dt;
gdvTM.DataBind();
}
protected void DropDownChange(object sender, EventArgs e)
{
this.BindGrid();
}

C# Nested Repeater not Working

I have been Looking around this for 3 days so please, any feed back will be appreciated .
I have a parent repeater that pulls the expected data but i am trying to nest a child repeater, Find the Control and Populate the data. but so far it has not worked. For Some Reason the Nested Repeater Below Is Not Being picked Up to display The Proper Data.
Any Suggestions?
Asp.Net Code Is Here:
<asp:Repeater ID="EquipmentRepeater" runat="server" OnItemDataBound="Repeater2_ItemDataBound" >
<ItemTemplate>
<b>Equipment:</b>
<%# DataBinder.Eval(Container.DataItem, "Equip") %>
<%# DataBinder.Eval(Container.DataItem, "Location") %>
</ItemTemplate>
</asp:Repeater>
protected void Repeater2_ItemDataBound(object sender System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
SqlConnection con = new SqlConnection(ConString);
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater Repeater2 = (Repeater)e.Item.FindControl("EquipmentRepeater");
System.Data.DataTable ds = new System.Data.DataTable();
SqlCommand cmd1 = new SqlCommand(" Select HourID, Equip,Location FROM Equip where HourID=#id");
cmd1.Parameters.Add("#id", SqlDbType.Int).Value = id;
con.Open();
cmd1.Connection = con;
cmd1.ExecuteReader();
con.Close();
SqlDataAdapter ad = new SqlDataAdapter(cmd1);
// DataTable ds = new DataTable();
ad.Fill(ds);
con.Close();
//Need to assign the Data in datatable
Repeater2.DataSource = ds;
Repeater2.DataBind();
}
}
I solved It, There were 2 Problems:
1- The Repeater ItemDataBound Needed to be in the parent repeater Even Handler.
2-the second Problem was The Id Parameter Id for The Child repeater did Not have any value So Icreated a hidden filed In the Parent repeater for Id and called it on ItemDataBound
<asp:HiddenField ID="ID" runat="server" Value='<%# Eval("ID") %>' />
protected void Repeater2_ItemDataBound(object sender System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
SqlConnection con = new SqlConnection(ConString);
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater Repeater2 = (Repeater)e.Item.FindControl("EquipmentRepeater");
System.Data.DataTable ds = new System.Data.DataTable();
SqlCommand cmd1 = new SqlCommand(" Select HourID, Equip,Location FROM Equip where HourID=#id");
HiddenField id = (HiddenField)e.Item.FindControl("ID");
int parsedId = int.Parse(id.Value);
cmd1.Parameters.Add("#id", SqlDbType.Int).Value = parsedId;
con.Open();
cmd1.Connection = con;
cmd1.ExecuteReader();
con.Close();
SqlDataAdapter ad = new SqlDataAdapter(cmd1);
// DataTable ds = new DataTable();
ad.Fill(ds);
con.Close();
//Need to assign the Data in datatable
Repeater2.DataSource = ds;
Repeater2.DataBind();
}
}
thank You all and good luck

GridViewRowCommand cant find header row textbox value

i am trying to insert into sql table using gridview header template, under the gridview rowcommand i am trying to find the control and it is not able to retrieve the value.
protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string NetWeightConnectionStrings = ConfigurationManager.ConnectionStrings["NetWeightConnectionString"].ToString();
string query = "INSERT INTO [Net Weight Tracking] ([Date])VALUES (#Date)";
using (SqlConnection sqlConn = new SqlConnection(NetWeightConnectionStrings))
using (SqlCommand cmd = new SqlCommand(query, sqlConn))
{
String Date = ((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.ParseExact(((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text, "dd/MM/yyyy", null);
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridV1.DataSource = dt;
GridV1.DataBind();
sqlConn.Close();
}
}
}
any help is much appreciated
You can try the RowDataBound Event to get the header template controls.
protected void GridView1__RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
TextBox txtControl = (TextBox)e.Row.FindControl("TextBox31");
}
}
EDIT 1
From the link shared for the GridView Mark up, TextBox31 is not in the HeaderItemTemplate, it is in EditItemTemplate. That would be the reason, you are not able to find the textbox.
<EditItemTemplate>
<asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
</EditItemTemplate>

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.

DropDownList.DataSource NullReferenceException?

I am getting null reference in by backend CS Code. Why is the DataTable null?
<asp:TemplateField HeaderText="Frequency" ItemStyle-Width = "150" >
<ItemTemplate>
<asp:Label ID="Frequency" runat="server" Text='<% # Eval("frequency") %>' ></asp:Label>
<asp:DropDownList ID="frequencydropdownlist" runat="server" Visible="false" ></asp:DropDownList>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="Addfrequencydropdownlist" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
</Columns>
Code Behind:
public partial class CollectionHead : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtt = new DataTable();
string conString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand mycommand = new SqlCommand();
mycommand.Connection = con;
mycommand.CommandText = "select ID,Frequency from FeesFrequency";
mycommand.CommandType = CommandType.Text;
mycommand.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = mycommand;
sda.Fill(dtt);
DropDownList Addfrequencydropdownlist = CollectionHead_GridView.FindControl("Addfrequencydropdownlist") as DropDownList;
Addfrequencydropdownlist.DataSource = dtt.DefaultView;// null reference exception ????????
Addfrequencydropdownlist.DataTextField = "Frequency";
Addfrequencydropdownlist.DataValueField = "ID";
Addfrequencydropdownlist.DataBind();
Update You have to databind the grid first before you can access it's footer. Therefore i would use the RowDataBound event to fill the DropDownList:
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList Addfrequencydropdownlist = (DropDownList)e.Row.FindControl("Addfrequencydropdownlist");
// ...
}
}
Old answer (might still be useful):
It is Addfrequencydropdownlist which is null after your try-cast because the NamingContainer of the DropDownList in the footer of the grid is not the grid itself but the FooterRow. So this is null causing the NullReferenceException:
CollectionHead_GridView.FindControl("Addfrequencydropdownlist")
You can use the FooterRow-property of the grid to get it's reference:
GridViewRow footer = CollectionHead_GridView.FooterRow;
DropDownList Addfrequencydropdownlist = (DropDownList)footer.FindControl("Addfrequencydropdownlist");
As an aside, i would use the as operator only if it isn't exceptional that it is null. Otherwise you're replacing a menaingful NullReferenceException with a bug in your code(in this case a NullReferenceException at the wrong place).
I would also wrap it in a if(!IsPostBack)-check to databind it only at the initial load and not on every postback if ViewState is enabled(default):
if(!IsPostBack)
{
DataTable dtt = new DataTable();
// rest of your code in Page_Load ....
}

Categories