set Dropdownlist SelectedIndex in a DataGrid

M

marcbb

Hi all,

I have a really strange problem working with Dropdownlists in a
DataGrid.

I'm trying to preselect some values from the DropDownlist for each
row in the DataGrid, but it seems that both selectedIndex has the same
reference and modifying the first one also automatically modify the
second one. For example:

A <DDL_1> <DDL_2>
B <DDL_1> <DDL_2>
... ... ...

For each row (i) in the DataGrid, I make:

[1]
//Get Dropdownlist 1
DropDownList ddl1 = (DropDownList)
dgList.Items.FindControl("DDL_1");

//Get Dropdownlist 2
DropDownList ddl2 = (DropDownList)
dgList.Items.FindControl("DDL_2");

and then, I preselect their SelectedIndex:

[2] I have this function for this:

public void SelectDropDownValue(DropDownList ddl, string
selectedValue)
{
ListItem li = null;
li = ddl.Items.FindByValue(selectedValue);
if (li != null)
{
int index = ddl.Items.IndexOf(li);
ddl.SelectedIndex = index;
}
}

when I make:

//here, ddl1.SelectedIndex = 0 and ddl2.SelectedIndex = 0

SelectDropDownValue(ddl1, val1); //after this, ddl1.SelectedIndex =
val1 and ddl2.SelectedIndex = 0


SelectDropDownValue(ddl2, val2); //after this, ddl1.SelectedIndex
= val2 and ddl2.SelectedIndex = val2

//after this, every change that i make to ddl1.SelectedIndex is also
affecting at the same time to ddl2.SelectedIndex and IDEM with
VICEVERSA.


Is it normal?

Thanks in advance
 
M

marcbb

Ok, finally I've resolved the problem.

It was at the initialization of the DDL in ItemDataBound function. I
was doing:

private void dgList_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
.....
ListItem li = new ListItem(valDesc, valId);
ddl1.Items.Add(li);
ddl2.Items.Add(li);
....
}

I was initializing both DropDownlists with the same object (ListItem
li). It makes its content has the same reference (or pointer) and
changing the content of one of them also mofify the other one because
they were pointing to the same place (or at least, it seemed).

Then, the solution was to initializate each control with a different
ListItem. Something like this:

private void dgList_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
.....
ListItem li = new ListItem(valDesc, valId);
ddl1.Items.Add(li);
ListItem li2 = new ListItem(valDesc, valId);
ddl2.Items.Add(li2);
....
}


Thanks for your attention.

Regards
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top