日期:2014-05-18  浏览次数:20419 次

为什么会这样?listbox无法获取到选中的项.......
情况:
listbox1根据dropdownlist的不同值绑定不同的数据,我想选中绑定后listbox1中的几项移动到listbox2里,可是总是将listbox1的第1项移动过去
单步调试了一下,发现listbox1如果有选中项的时候,它的选中项总是第一项

在if(!this.ispostback)里面给listbox1绑定的数据的时候却可以正常移动
也就是说   在DropDownList1_SelectedIndexChanged事件里有什么原因导致了listbox1无法获取选中项

private   void   DropDownList1_SelectedIndexChanged(object   sender,   System.EventArgs   e)
{
SqlConnection   con=DB.createcon();
con.Open();
SqlDataAdapter   sda=new   SqlDataAdapter();
DataSet   ds=new   DataSet();
string   planfor=this.DropDownList1.SelectedValue.ToString();
if(planfor== "请选择监控对象 ")
{
this.ListBox1.Items.Clear();
this.ListBox2.Items.Clear();
}
else
{
this.ListBox1.Items.Clear();
sda.SelectCommand=new   SqlCommand( "select   Item,Method   from   Item   where   PlanForID   like   '% "+planfor+ "% ' ",con);
sda.Fill(ds, "item ");
this.ListBox2.DataTextField= "Item ";
this.ListBox2.DataValueField= "Method ";
this.ListBox2.DataSource=ds.Tables[ "item "].DefaultView;
this.ListBox2.DataBind();
}
con.Close();
}

求教

------解决方案--------------------
我觉得不是绑定的问题...
首先,你是在页面回传的时候有重新绑定过listbox呢?如果有,则listbox选中的行应该都被重新摧毁了...如果没有,应该检查下转移的函数...
------解决方案--------------------
private void GleftRight(ListBox oldListB,ListBox newListB)
{
bool IsHas = false;
foreach(ListItem mItem in oldListB.Items)
{
if(mItem.Selected)
{
IsHas = false;
foreach(ListItem lItem in newListB.Items)
{
if(mItem.Value == lItem.Value)
{
IsHas = true;
}
}
if(!IsHas)
{
newListB.Items.Add(mItem);
}
oldListB.Items.Remove(mItem);
newListB.SelectedIndex = -1;
oldListB.SelectedIndex = -1;
return;
}
}
}
------解决方案--------------------
问题的原因就是因为回传的时候重新绑定了ListBox,所以才会出现被选项为第一项的情况。所以你必须把绑定的代码写在
if(!ispostback)
{
}
块里面!!!
------解决方案--------------------
DropDownList1_SelectedIndexChanged 中listbox1 的item都clear 掉了, 什么时候再加上去的呢? 难道是Page_load中没有加if(!this.PostBack)?
------解决方案--------------------
<script language= "javascript ">
function checkdate(){
var tt = document.getElementById( "rebuildTime ").value;
var dt = document.getElementById( "DeployDate ").value;
if(strToDate(tt) > strToDate(dt)){
//alert( "对不起,测试时间不能大于上线时间 ");
//span1.innerHTML = "对不起,改造完成时间不能大于上线时间 ";
}
}
function strToDate(str){
var arr=str.split( "- ");
return new Date(arr[0],arr[1],arr[2]);
}
function Add(ObjSource,ObjTarget){
var str = " ";
for(var i=ObjSource.length-1;i> =0;i--){
if(ObjSource.options[i].selected){
ObjTarget.add(new Option(ObjSource.options[i].text,ObjSource.options[i].value,true));
ObjSource.options.removeChild(ObjSource.options[i]);
}
}

}
function AddAll(ObjSource,ObjTarget){
SelectAll(ObjSource);