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.
Related
I have a gridView, and inside is there exist a modifiable textbox.
I also have a dropdownlist, where if I click the dropdownlist, the system will read the database in SQL and display it in gridView.
How do I keep the number I previously typed in the first row of the gridView, when a new data is added after the dropdownlist is clicked?
Normally, the previously entered value of the textbox will be resetted if i rebind the gridView witthout refilling the textbox with a saved list or behaviour
Thank you very much in advance
I'm assuming you are using something like the OnSelectedIndexChanged event of the DropDownList. In there you can use FindControl to find the TextBox, store the data, rebind the GridView and set the value back to the TextBox. You need to use FindControl twice, one for the old and once for the new TextBox.
Note the use of oldValues.Count instead of GridView1.Rows.Count. If there were less rows in the new dataset than in the old you would get Index out of Bounds error.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> oldValues = new List<string>();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
TextBox tbOld = GridView1.Rows[i].FindControl("TextBox1") as TextBox;
oldValues.Add(tbOld.Text);
}
//rebind gridview here
for (int i = 0; i < oldValues.Count; i++)
{
TextBox tbNew = GridView1.Rows[i].FindControl("TextBox1") as TextBox;
tbNew.Text = oldValues[i];
}
}
You have used dropdownlist and textbox inside gridview?
if you click dropdownlist select value then postback to server and textbox value reset?
For the life of me I cannot seem to figure this out. I have a long DataGridView (that does not allow MultiSelect) and when a user commits a change to the data, the data from the grid is purged and redrawn (because changes can affect multiple rows, this was the simpler approach). However, when I try to select the row programmatically, it does not also fire the DataGridView.SelectionChanged event, which I use to display data from an array which is correlated to the DataGridView current cell index. When doMagicStuff executes, the values for the wrong index (specifically, index 0) is show.
private void doMagicStuff()
{
int selRow = myDGV.CurrentCell.RowIndex;
myDGV.Rows.Clear();
/*Perform Task, Redraw data*/
myDGV.CurrentCell = myDGV[selRow, 0];
}
private void myDGV_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = myDisplayValue1[myDGV.CurrentCell.RowIndex];
Label2.Text = myDisplayValue2[myDGV.CurrentCell.RowIndex];
TextBox1.Text = myEditValue1[myDGV.CurrentCell.RowIndex];
TextBox2.Text = myEditValue2[myDGV.CurrentCell.RowIndex];
}
Make sure that your client settings and OnSelectedIndexChanged is set like so: (ASP.NET AJAX)
.aspx page
<telerik:RadGrid ID="Grid1" runat="server" OnSelectedIndexChanged="Grid1_SelectedIndexChanged" OnItemDataBound="Grid1_ItemDataBound" OnPreRender="Grid1_PreRender">
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true"></Selecting>
</ClientSettings>
</telerik:RadGrid>
aspx.cs page
protected void Grid1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
foreach(GridDataItem item in Grid1.SelectedItems)
{
//column name is in doub quotes
value = item["Name"].Text;
}
}
Add a button click to the form to test the selected values in the DataGridView.. double click that button then paste this code in there
foreach (DataGridViewRow row in myDGV.SelectedRows)
{
Label1.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
Label2.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
TextBox1.Text = row.Cells[0].Value.ToString();//change the 0 or 1 to fit your column Index position
TextBox2.Text = row.Cells[2].Value.ToString();
}
also if you have 4 columns and 4 text boxes then you will assign all of the textbox.Text values within the foreach loop just follow the pattern and increase the index by 1 so 2 textboxes means row.Cells[0] is the first column row.Cells[1] is the second column ...etc
I am working on ASP.NET C# web application. I have a DropDownList for selecting machines_names that is Databound. And a gridview which displays stored data. Gridview also contains templateField for Edit and Delete Buttons. When Edit Button is clicked the stored values of respective fields must be must be loaded on respective field in web form. The problem is when I click edit button, item in ddl (the default value "--select--") is replaced by current data.
I want the stored ddl item to be selected in the ddl when the edit button is clicked.
For example in ddl there are items such as
--select--
Roller
Heater
sensor
In grid view I have the following
Repair-id machine
1 roller
2 sensor
So when I click edit button of ID 2 in grid view, the ddl must select the third item ie sensor without replacing the top item in ddl.
Here's my code
protected DataTable bindMachineName()
{
DataTable dt = new DataTable();
dc.Company_code = Convert.ToInt32(Session["Company_Code"].ToString());
dt = dpbll.select_machine_name(dc);
ddlMachine.DataSource = dt;
ddlMachine.DataTextField = "machine_name";
ddlMachine.DataValueField = "machine_id";
ddlMachine.DataBind();
ddlMachine.Items.Insert(0, new ListItem("----- Select -----", "-1"));
return dt;
}
protected void btnEdit_Click(object sender, EventArgs e)
{
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string repair_id = gv.Cells[0].Text;
ViewState["repair_id"] = repair_id;
ddlMachine.SelectedItem.Text = gv.Cells[1].Text;
}
Nevermind I solved the problem.
ddlMachine.Items.FindByText(gv.Cells[1].Text did work perfectly.
protected void btnEdit_Click(object sender, EventArgs e)
{
dc.Company_code = Convert.ToInt32(Session["company_code"].ToString());
Button btn = (Button)sender;
GridViewRow gv = (GridViewRow)btn.NamingContainer;
string repair_id = gv.Cells[0].Text;
ViewState["repair_id"] = repair_id;
ddlMachine.SelectedIndex=ddlMachine.Items.IndexOf(ddlMachine.Items.FindByText(gv.Cells[1].Text));
}
The problem is when I click edit button, item in ddl (the default
value "--select--") is replaced by current data.
You might want to set the DropDownList's AppendDataBoundItems to true.
<asp:DropDownList runat="server" ID="ddlMachine" AppendDataBoundItems="true">
<asp:ListItem Text="----- Select -----" Value="-1" />
</asp:DropDownList>
The AppendDataBoundItems property allows you to add items to the
ListControl object before data binding occurs. After data binding, the
items collection contains both the items from the data source and the
previously added items.
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.
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.