电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

DropdownList绑定的两种方法


发布日期:2020/6/25
 
DropdownList绑定的两种方法

动态绑定方法一动态绑定数据库中的字段

SqlConnection conn = UtilitySqlClassOperateDataBaseReturnConn();

string strSQL = select * from CompanyType;

SqlDataAdapter ada = new SqlDataAdapter(strSQL conn);

DataSet ds = new DataSet();

adaFill(ds CompanyType);

DropDownListDataSource = dsTables[CompanyType]DefaultView;

DropDownListDataValueField = dsTables[CompanyType]Columns[]ColumnName;

DropDownListDataTextField = dsTables[CompanyType]Columns[]ColumnName;

DropDownListDataBind();

dsDispose();

动态绑定方法二利用DropDownListItemsAdd方法

PRotected void Page_Load(object sender EventArgs e)

{

if (!IsPostBack)

{

SqlConnection conn = UtilitySqlClassOperateDataBaseReturnConn();

try

{

connOpen();

thisDropDownListItemsAdd();

string strSQL = select CompanyType from CompanyType;

SqlCommand com = new SqlCommand(strSQL conn);

SqlDataReader dr = comExecuteReader();

while (drRead())

{

thisDropDownListItemsAdd(dr[CompanyType]ToString());

}

}

catch (Exception ex)

{

ResponseWrite(<scirpt>alert( + exMessageToString() + )</script>);

}

finally

{

connClose();

}

}

}

第一种方法

string ConnString = ConfigurationSettingsAppSettings[ConnectionString];

//创建一个SqlConnection

SqlConnection Conn = new SqlConnection( ConnString );

string SQL_Select = select id ItemName from DDLItem order by id desc;

//构造一个SqlDataAdapter

SqlDataAdapter myAdapter = new SqlDataAdapter( SQL_Select Conn);

//开始读取数据

ConnOpen();

DataSet dataSet = new DataSet();

myAdapterFill( dataSetTable );

ConnClose();

//开始绑定DropDownList

//指定DropDownList使用的数据源

DropDownListDataSource = dataSetTables[Table]DefaultView;

//指定DropDownList使用的表里的那些字段

DropDownListDataTextField = ItemName; //dropdownlist的Text的字段

DropDownListDataValueField = id;//dropdownlist的Value的字段

DropDownListDataBind();

第二种方法

conOpen();

SqlCommand cmd = new SqlCommand(strSqlcon);

SqlDataReader dr = cmdExecuteReader();

while (drRead())

{

DropDownListItemsAdd(new ListItem(dr[status]ToString() dr[status_Id]ToString()));

}

上一篇:sealed、new、virtual、abstract 和 override

下一篇:MS Chart的常用属性和事件