DropDownList getting a blank selection - c#

I have a dropdownlist populated by code, directly from the database. But there's a selectable item with no value, at the bottom. How can I bind the data from the database purely / entirely to avoid getting this blank selection in the future?
protected void DropDownList_OnDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlName = (DropDownList)e.Row.FindControl("ddlName");
ddlName.DataSource = MyClass.NameList();
ddlName.DataTextField = "Name";
ddlName.DataValueField = "id";
ddlName.DataBind();
}
}

Try to remove your code declaration '< asp:DropDownList >' and type it again. This will refresh your dropdownlist from scratch, clearing all its reference upon deleting it. Your current dropdownlist may be taking a reference somewhere along the development of your project.

Make sure NameList() method doesnot return any null values.

Related

Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlForm' to type 'System.Web.UI.WebControls.GridViewRow'

Here is my ASP.NET code snippet.
I am trying to select a GridView Row and add the selected row items in Session Variable.
// ======================== MyGridView ========================
protected void GridView_MyGridView_SelectedIndexChanged(object sender, EventArgs e)
{
// Get Selected Row Items
Items myitems = new Items();
Session["Items"] = myitems;
((Invoices)Session["Items"]).ItemNo = int.Parse(((GridViewRow)(((WebControl)(sender)).Parent.Parent)).Cells[0].Text);
}
I do NOT want to use the clickable select button that comes with the GridView Columns.
I handled by the following code:
protected void GridView_MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.ToolTip = "Click to Select a Visit.";
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(sender as GridView, "SELECT$" + e.Row.RowIndex);
}
}
Now, when I run the program, I get the following error as soon as the gridview selected row changes:
Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlForm' to type 'System.Web.UI.WebControls.GridViewRow'.
Please, provide your feedback.
Not sure what you are trying to do but your cast is what is causing it. Your call to Parent.Parent is going too far up the tree and you have ended up with the form container and are no longer within the GridView at all.
Instead of the cast you are attempting, why not just try:
GridViewRow row = GridView_MyGridView.SelectedRow;
((Invoices)Session["Items"]).ItemNo = int.Parse(row.Cells[0].Text);
Keep in mind, this will still error out if there is no text in the cell so you may want to look at handling that with additional logic or a TryParse() instead.

How to update the value of a Label in footer template of a gridview?

I have a Gridview that has editable fields in it am calculating the sum of every column and displaying it in the footer columns my gridview column looks like
This is not updating the value can anyone please help me where i should correct my code?
if (i == objGrid.rows.length)
{
objGrid.rows[i].cells[2].children[0].innerText = ClsSum;
objGrid.rows[i].cells[3].children[0].innerText = NonSaleSum;
objGrid.rows[i].cells[7].children[0].innerText = SecSum;
}
You can check for the rows.length -1.
And make sure that the code snippet will get executed after the postback.
I hope this code executes after you bind your gridview . So please check if you have applied
(!IsPostBack) in your GridviewBind method .
Also check does if your code reaches this method when reloads or updates your values ?
You can try this also, put below code out side of loop
//create css class called "footerClass" and apply on column fotter template
var objGrid= document.getElementById('<%=YourGrid.ClientID%>');
var cells = objGrid.getElementsByClassName('footerClass')
cells[0].innerText = ClsSum;
cells[1].innerText = NonSaleSum;
cells[2].innerText = SecSum;
I hope you are using Grid_RowDataBound() event and accordingly that you can try this
protected void Grid_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
e.Row.cells[2].children[0].innerText = ClsSum;
e.Row.cells[3].children[0].innerText = NonSaleSum;
e.Row.cells[7].children[0].innerText = SecSum;
}
}

ASP dynamic DropDownList selected index

My web form starts out as two TextBoxes, two Buttons, a CheckBoxList (bound to the results of a database query), and an empty DropDownList.
When the user enters a search phrase into the first TextBox and hits enter (or clicks the first Button, "Search"), a GridView appears, populated with rows pulled from the database. When the user hits the Select button on one of the rows, the DropDownList is populated (bound to results of a database query) and enabled (if the query returned results -- if there were no results, it remains disabled). When the second Button ("Save Settings") is clicked, the relevant data is saved to the DB, the GridView's selection is cleared, and the DropDownList is cleared and disabled.
All of the above works. The problem comes from the DropDownList. I can't get the C# code to recognize the changing SelectedIndex; depending on how I shuffle my code around, the index is always either 0 (and the DropDownList is forced to stay on the first item), or -1 (and the list becomes disabled).
DropDownList code:
<asp:DropDownList ID="myList" runat="server" AutoPostBack="True"
DataTextField="MyName" DataValueField="MyID"
Enabled="False" onselectedindexchanged="myList_SelectedIndexChanged" />
C# code:
protected void myGrid_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
if (myGrid.SelectedIndex >= 0)
{
int id = int.Parse(myGrid.Rows[myGrid.SelectedIndex].Cells[2].Text);
connection.Open();
string query = "..."; // Omitted for brevity; the query is correct
SqlDataSource source = new SqlDataSource(connectionString, query);
source.SelectParameters.Add("Param1", TypeCode.String, id.ToString());
DataTable dt = ((DataView)source.Select(DataSourceSelectArguments.Empty)).Table;
dt.AcceptChanges();
myList.DataSource = dt;
myList.DataBind();
myList.Enabled = myList.Items.Count != 0;
if (!myList.Enabled)
{
myList.Items.Add(new ListItem("No Results", "0"));
}
}
}
}
protected void myList_SelectedIndexChanged(object sender, EventArgs e)
{
// ((DropDownList)sender).SelectedIndex == -1
}
I've read that there are some problems with DropDownList while searching for a solution to my problem, but besides the note to set AutoPostBack="True", none of the other situations I've found have helped.
One common reason on why the DropDownList loses its SelectedIndex value is, that during the postback is binded again with data. Do you populate data to the DropDownList somewhere else in your code? Maybe there is something else that causes the SelectedIndex event of the GridView to fire again?
Another thought is that changing the Enabled status of the DropDownList might cause this behavior. Try your code without disabling the DropDownList, and see if something changes.

Get the value/text of a column in a Gridview in ASP.net C# to display in a label

I have a gridview that has a list of Salesman names. When a Salesman is selected using A ButtonFieldTemplate in the Grid. I need the name of selected Salesman to appear in a Label.
So far I have this but it is not working:
protected void gvSalesmanByManager_SelectedIndexChanged(object sender, EventArgs e)
{
lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedValue + "'s Customers";
}
It's not throwing any errors. Not even red squiggly lines in Visual Studio. It's just plain not working.
How can I accomplish this in ASP.net and C# 4.0.
Regarding to the documentation SelectedValue gets the data key value of the selected row in a GridView control. Does your GridView contain a column with the key and did you set the dataKeyNamesProperty (such as datakeynames="myID")?
EDIT:
To access a value of a column you can use SelectedRow:
GridViewRow row = GridView1.SelectedRow;
lblSalesmanCustomers.Text = row.Cells[2].Text;
EDIT2:
There are two options when you want to read the template field. Either you store your value in an additional invisible column or you access the controls inside the template field. Something like this should work:
lblSalesmanCustomers.Text = ((TextBox)row.Cells[2].FindContol("tbxName")).Text;
Make sure you are not assigning empty text on page load event.
or you need to place those initialization in if(!Page.IsPostback) block
My code so far : protected void gvSalesmanByManager_SelectedIndexChanged(object sender, EventArgs e) { lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedValue + "'s Customers"; } –
try in the event "gvSalesmanByManager_SelectedIndexChanged" following code:
lblSalesmanCustomers.Text = gvSalesmanByManager.SelectedRow.Cells[0].Text;
You said something about a "ButtonFieldTemplate" please show me some code from your ascx-file this will help us much i think.
*Edit:
"Controls[1]" has not to be right. But 0 is a literal. you could also debug your code and set breakpoints. would be much easier.
try this with Linkbutton:
LinkButton lnk1 = gvSalesmanByManager.SelectedRow.Cells[0].Controls[1] as LinkButton;
lblSalesmanCustomers.Text = lnk1.Text;
best regards,
noone

selected index of DDL is always equal to Zero in asp .net

I have a Program Class, with properties as Id, ProgramName,ShortName and Code, im my app
I have a ASP DDL like
<asp:DropDownList ID="DDLProgram" runat="server"
OnSelectedIndexChanged ="OnDDLProgramChanged" AutoPostBack = "true">
</asp:DropDownList>
My OnDDLProgramChanged method is defined as
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
//My Problem goes here
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
My list is getting all the records correctly, I have checked it. But whenever I am changing an item in the DDL, the selected index in not changing. The selected index is remaining zero.Therefore, I am not being able to get the code of other items but the 0 index's item.
Can anyone help me in this case?
You are binding the data again in your selectedIndex Change event and it will reset your current SelectedIndex after rebinding. You don't need to rebind the data to your dropdown in SelectedIndex Change Event
It should be like..
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
You have to bind data to the DropDownList on page load method
if (!IsPostBack)
{
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
}
Otherwise it will bind data everytime and hence clear the selection
Why are you assigning the DataSource in OnDDLProgramChanged, this would be resetting the selection you make.

Categories

Resources