日期:2014-05-20  浏览次数:20418 次

编辑GridView中DropDownList如何实现数据库中默认值?
在GridView中的EditItemTemplate放入一DropDownList,DropDownList通过方法绑定数据,请教DropDownList如何实现默认所在的数据值?

------解决方案--------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex == GridView1.EditIndex)
{

DataRowView rowItem = (DataRowView)e.Row.DataItem;

DropDownList clsName = (DropDownList)e.Row.FindControl( "uClassName ");
if (rowItem[ "ClassName "] != DBNull.Value)
{
clsName.Items.FindByText(rowItem[ "ClassName "].ToString()).Selected = true;
}

}
}
}
------解决方案--------------------
不用谢,OK了.我自定义了2个DataTable你将他换成你的就行了
1: .cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.GridView1.DataBind();

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
int rid = Convert.ToInt32(((DataRowView)e.Row.DataItem)[ "Rid "]);
DropDownList dd = (DropDownList)e.Row.FindControl( "DropDownList2 ");
DataTable table = dd.DataSource as DataTable;
dd.SelectedIndex = table.Rows.IndexOf(table.Rows.Find(rid));
}
}
public DataTable GridSource
{
get
{
DataTable table = new DataTable();
table.Columns.Add( "ID ", typeof(int));
table.Columns.Add( "Rid ", typeof(int));
for (int i = 1; i < 3; i++)
{
DataRow row = table.NewRow();
row[ "ID "] = i;
row[ "Rid "] = i;
table.Rows.Add(row);
}
return table;
}
}
public DataTable DropSource
{
get
{
DataTable table = new DataTable();
DataColumn col=new DataColumn( "Rid ", typeof(int));
table.Columns.Add(col);
table.PrimaryKey = new DataColumn[] { col };
table.Columns.Add( "Rname ", typeof(string));
for (int i = 1; i < 3; i++)
{
DataRow row = table.NewRow();
row[ "Rid "] = i;
row[ "Rname "] = i+ "aa ";
table.Rows.Add(row);
}
return table;
}
}
2:页面
<asp:GridView ID= "GridView1 " DataSource= " <%# GridSource %> " runat= "server " OnRowDataBound= "GridView1_RowDataBound " AutoGenerateColumns= "false ">

<Columns>
<asp:BoundField DataField= "ID " />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID= "DropDownList2 " DataSource= " <%#DropSource %> " DataTextField= "Rname " DataValueField= "Rid " runat= "server ">
</asp:DropDownList>

</ItemTemplate>