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

gridView 添加dropDownList里的一些问题,
一个新闻列表,我用是的gridview做的。其中有一个新闻类型列。我点击编辑时。希望出现的不是文本框,而是下拉框。

在网上找了一天的资料基本现实,但感觉不太好。所以再来请教一下:

我是这样实现的:

首先把类型弄成模板列,然后在编辑模板中加上ddl,然后在每行数据绑定时给DDL 里绑定数据,代码如下:

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {

  DropDownList ddlClassName = e.Row.FindControl("ddlClassName") as DropDownList;
  if (ddlClassName != null)
  {
  myDb a = new myDb();
  ddlClassName.DataSource = a.getNewsClass();
  ddlClassName.DataTextField = "NewsClassName";
  ddlClassName.DataValueField = "NewsClassName";
  ddlClassName.DataBind();
  }


但有几个疑问? DDL的绑定.如放在RowDataBound这个事件中,那不是每行的ddl都绑定了数据吗?是不是太浪费了,应该是要修改哪条就给那条绑才对..
第二:怎么设置ddlClassName的默认项为没编辑时的文本显示的那项..

谢谢

------解决方案--------------------
asp页面
<asp:TemplateField HeaderText="Image1">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("trendanalysisImage1") %>' ReadOnly="True" Visible="false"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="0" Selected="True" >images/up.jpg</asp:ListItem>
<asp:ListItem Value="1">images/down.jpg</asp:ListItem>
<asp:ListItem Value="2">images/flat.jpg</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("trendanalysisImage1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>

RowDataBound事件
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView1.EditIndex != -1 && GridView1.EditIndex == e.Row.RowIndex)
{
string image="";
TextBox tb = (TextBox)e.Row.FindControl("TextBox2");
if (tb != null)
{
image = tb.Text.Trim();
}
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
if (ddl != null)
{
for (int i = 0; i < ddl.Items.Count; i++)
{
ddl.Items[i].Selected = false;
if (image == ddl.Items[i].Text)
{
ddl.Items[i].Selected = true;
}
}
}
}
}

RowUpdating事件
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

string ID = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
string Image1 = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDownList1")).SelectedItem.Text.Trim();
string str = "update trendanalysis set trendanalysisName='"+Name+"', trendanalysisImage1='" + Image1 + "',trendanalysisImage2='" + Image2 + "',trendanalysisImage3='" + Image3 + "',trendanalysisImage4='" + Image4 + "' where trendanalysisID=" + ID + "";