我在点击按钮后尝试删除列表框中的所选项目。但我失败了。
此代码有什么问题?
删除功能
public void RemoveFromList()
{
int c = listNotMatchedItems.Items.Count - 1;
for (int i = c; i >= 0; i++)
{
listNotMatchedItems.Items.RemoveAt(i);
}
}
点击按钮
private void AddToAnotherList_Click(object sender, EventArgs e)
{
//Add to another list.some codes....
RemoveFromList();
}
答案 0 :(得分:1)
问题:您的函数RemoveFromList()
会从ListBox中删除所有项目。
解决方案:如果您只想删除所选项目,请使用ListBox1.SelectedIndex
获取所选项目索引并将其传递给ListBox1.Items.RemoveAt()
方法。
试试这个:
private void AddToAnotherList_Click(object sender, EventArgs e)
{
//Add to another list.some codes....
listNotMatchedItems.Items.RemoveAt(listNotMatchedItems.SelectedIndex);
}
您的listNotMatchedItems_SelectedIndexChanged
事件处理程序中的编辑
替换它:
string table = listNotMatchedItems.SelectedItem.ToString();
有了这个:
private void listNotMatchedItems_SelectedIndexChanged(object sender, EventArgs e)
{
string table =String.Empty;
if(listNotMatchedItems.SelectedItems.Count>0)
{
using (SqlConnection con = new SqlConnection(strConnectDB1))
{
con.Open();
using (SqlCommand comQuery = new SqlCommand(@" declare @vsSQL varchar(8000)
declare @vsTableName varchar(50)
select @vsTableName = @TT
select @vsSQL = 'CREATE TABLE ' + @vsTableName + char(10) + '(' + char(10)
select @vsSQL = @vsSQL + ' ' + sc.Name + ' ' +
st.Name +
case when st.Name in ('varchar','varchar','char','nchar') then '(' + cast(sc.Length as varchar) + ') ' else ' ' end +
case when sc.IsNullable = 1 then 'NULL' else 'NOT NULL' end + ',' + char(10)
from sysobjects so
join syscolumns sc on sc.id = so.id
join systypes st on st.xusertype = sc.xusertype
where so.name = @vsTableName
order by
sc.ColID
select substring(@vsSQL,1,len(@vsSQL) - 2) + char(10) + ')'", con))
{
comQuery.Parameters.AddWithValue("@TT", listNotMatchedItems.SelectedItem);
using (SqlDataReader readerQuery = comQuery.ExecuteReader())
{
txtNotMachedQuery.Text = "";
int a = 0;
while (readerQuery.Read())
{
a++;
txtNotMachedQuery.Text = readerQuery[0].ToString() ;
}
}
}
using (SqlCommand com = new SqlCommand(@"SELECT * FROM " + table, con))
{
using (SqlDataReader reader = com.ExecuteReader(CommandBehavior.SchemaOnly))
{
listNotMachedFields.Items.Clear();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow colRow in schemaTable.Rows)
listNotMachedFields.Items.Add(colRow.Field<String>("ColumnName"));
}
}
}
}//if end
}
编辑2:
替换它:
comQuery.Parameters.AddWithValue("@TT", listNotMatchedItems.SelectedItem);
有了这个:
comQuery.Parameters.AddWithValue("@TT", listNotMatchedItems.SelectedValue.ToString());