ListBox - 将值设置为文本字段

时间:2011-03-03 21:14:35

标签: c# asp.net data-binding listbox

问题: 添加列表项时,“值”字段将设置为“文本”字段。最初我虽然问题与主键(group_type_id)的输入参数有关,因为它被配置为OUTPUT变量。

有趣的是,当我观察所有的价值观时,一切都是正确的。 例如,我会看这些:

ddr["group_type_name"]   comes out as "Dept"
ddr["grouptypeid"] comes out as 4

但是,当创建项目时,

itms.TEXT = "Dept"
itms.Value = "Dept"  <-- THIS IS THE PROBLEM

当我可以清楚地看到数据读取器值正确时,我很遗憾为什么列表框值被设置为文本值。 ?

此处的代码示例:

DbDataReader ddr = grp.GetGroupTypeList(grp);
if (ddr.HasRows)
{
    ListItem itm = new ListItem();
    itm.Text = "Select Group";
    itm.Value = "0";
    lb.Items.Add(itm);
    while (ddr.Read())
    {
        ListItem itms = new ListItem(ddr["group_type_name"] as string, ddr["grouptypeid"] as string);
    }
    lb.SelectedValue = lbSelected;            
}

程序:

ALTER PROCEDURE [dbo].[asp_Group_Type]
@driver             char(1)='I',
@group_type_id      int=null OUTPUT,
@group_type_name    varchar(50)=null,
@par_group_id       int=null,
@active             bit 
AS
DECLARE @SQL    varchar(8000)
DECLARE @boolWhere varchar(10)
SET @boolWhere = ' WHERE ' 

SET NOCOUNT ON

IF (@driver = 'I')
    BEGIN
        INSERT INTO  [dbo].[group_type]
       ([group_type_name],
        [Par_Group_Id])
     VALUES
       (RTRIM(LTRIM(@group_type_name)),
        @par_group_id)

        SELECT @group_type_id = SCOPE_IDENTITY() 
    END

IF (@driver = 'U')
    BEGIN
        UPDATE  [dbo].[group_type]
           SET [group_type_name] = RTRIM(LTRIM(@group_type_name))
              ,[Par_Group_Id] = @par_group_id
         WHERE [group_type_id] = @group_type_id
    END

IF (@driver = 'S')
    BEGIN


        SET @SQL = ' SELECT  [group_type_id] AS [grouptypeid], [group_type_id], [group_type_name],[Par_Group_Id]  FROM [dbo].[group_type] '

        IF (@group_type_id > 0)
            BEGIN
                SET @SQL = @SQL + @boolWhere + '[group_type_id] = ''' + CAST(@group_type_id AS VARCHAR) + ''''
                SET @boolWhere = ' AND '
            END 

        IF (@active > 0)
            BEGIN
        SET @SQL = @SQL + @boolWhere + ' [active] = ''' + CAST(@active AS VARCHAR) + ''''
            END 

        SET @SQL = @SQL + ' ORDER BY [group_type_name] '
        PRINT(@SQL)
        EXEC(@SQL)
    END

1 个答案:

答案 0 :(得分:0)

几乎可以肯定是导致问题的as string。如果无法执行转换,“as”将默认为null。如果Value不是有效字符串,ListItem将Value设置为与Text相同。而是使用ddr["grouptypeid"].ToString()