问题一:
protected voidgrdVoucher_RowDataBound(object sender, GridViewRowEventArgse)
{
DropDownList dropList =(DropDownList)e.Row.FindControl("dropZT");
if (dropList != null)
{
ListItem item1 = new ListItem("1", "1");
ListItem item2 = new ListItem("2", "2");
ListItem item3 = new ListItem("3", "3");
//DropDownList dropList =(DropDownList)e.Row.Cells[5].FindControl("dropZT");
dropList.Items.Add(item1);
dropList.Items.Add(item2);
dropList.Items.Add(item3);
dropList.DataBind();
}
}
为什么不做判断就会出错。怎么运行的。
是这样的:当窗体开始加载的时候,GridView绑定数据——引发行绑定事件——这时就像一个for循环,每个行、每个列挨着就行绑定,不可能一下子就找到DropDownList;再说只有点击了编辑项之后,DropDownList才会出现,即才会new出来,你找啥啊找。
所以必须判断之。
问题二:
我选择了DropDownList的项之后,然后点更新,为什么数据总是更新成为DropDownList的第一条呢?
那是因为不论是点击了更新还是编辑,他们都会自动回发,即引发窗体加载事件,而你有没有在窗体回发事件中做判断:if(!IsPostBack),而是又重新绑定了GridView的数据源,即又重新刷新了一次页面,DropDownList当然会默认选择了第一项,而你以前所选的项就取消了。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
好长时间不做,再做的话就花很多的时间,把样本代码复制下来当作备案吧。
aspx里面的代码:
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1"runat="server">
<div>
<asp:Label ID="Label1" runat="server"Style="z-index: 100; left: 223px; position: absolute;
top: 104px"Text="代理证"></asp:Label>
<asp:TextBox ID="txtPermit" runat="server"Style="z-index: 101; left: 341px; position: absolute;
top:102px"></asp:TextBox>
<asp:Label ID="Label2" runat="server"Style="z-index: 102; left: 625px; position: absolute;
top: 104px"Text="暂住证"></asp:Label>
<asp:TextBox ID="txtTemporary" runat="server"Style="z-index: 103; left: 732px; position: absolute;
top:102px"></asp:TextBox>
<asp:GridView ID="grdVoucher" runat="server" BackColor="White"
BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"CellPadding="3" CellSpacing="1"
GridLines="None" OnRowEditing="grdVoucher_RowEditing"Style="z-index: 104;
left: 36px; position: absolute; top: 175px; height: 131px; width:1095px;"
OnRowCancelingEdit="grdVoucher_RowCancelingEdit"
OnRowUpdating="grdVoucher_RowUpdating"DataKeyNames="c_wzbh"
OnRowDataBound="grdVoucher_RowDataBound"
onrowdeleting="grdVoucher_RowDeleting">
<RowStyle BackColor="#DEDFDE" ForeColor="Black"/>
<Columns>
<asp:BoundField DataField="c_wzbh" HeaderText="违章编号"ReadOnly="True" />
<asp:BoundField DataField="C_CPH" HeaderText="车牌号"ReadOnly="True" />
<asp:BoundField DataField="C_JSY" HeaderText="驾驶员"ReadOnly="True" />
<asp:BoundField DataField="C_WZDD" HeaderText="违章地点"ReadOnly="True" />