C# 如何正确地对gridview进行数据绑定?
所以我有一个包含gridview的页面,girdview通过web服务从objectdatasource获取它的数据。它包含2列和itemtemplates。对于处于编辑模式的每个模板,包含存储在edititemtemplates下的DropDownList 一切似乎都很正常,除了当我处于编辑模式并触发更新事件时,我的dropdownlists抛出一个空引用错误。经进一步调查,这似乎是由于暗藏思维无法找到投药者造成的。此外,在调试器中挖掘时,dropdownlists似乎根本不存在。 虽然,在我的页面上,DropDownList在编辑模式下显示,但codebehind无法定位这些控件 我猜我是在错误的位置绑定gridview,或者绑定本身做得不正确 我想知道的是,为什么会出现这种情况,我该如何解决? 如果有人能让我知道我的绑定是否正确,我也将不胜感激 下面您将找到我的gridview和它的codebehind代码 GridView:C# 如何正确地对gridview进行数据绑定?,c#,asp.net,C#,Asp.net,所以我有一个包含gridview的页面,girdview通过web服务从objectdatasource获取它的数据。它包含2列和itemtemplates。对于处于编辑模式的每个模板,包含存储在edititemtemplates下的DropDownList 一切似乎都很正常,除了当我处于编辑模式并触发更新事件时,我的dropdownlists抛出一个空引用错误。经进一步调查,这似乎是由于暗藏思维无法找到投药者造成的。此外,在调试器中挖掘时,dropdownlists似乎根本不存在。 虽然,在我
<asp:GridView ID="GridViewHolder"
runat="server"
AllowPaging="True"
AutoGenerateColumns="False"
BackColor="Transparent"
BorderColor="#999999"
BorderStyle="Ridge"
BorderWidth="3px"
CellPadding="4"
CellSpacing="2"
DataSourceID="MachineDataSet"
ForeColor="Black"
HeaderStyle-HorizontalAlign="Center"
HorizontalAlign="Center"
RowStyle-HorizontalAlign="Center"
Width="796px"
OnRowUpdating="GridViewHolder_Updating"
OnRowCancelingEdit="GridViewHolder_Canceling"
OnRowEditing="GridViewHolder_Editing"
OnRowCommand="GridViewHolder_RowCommand"
EnableViewState="False">
<RowStyle BackColor="Transparent"
HorizontalAlign="Center" />
<Columns>
<asp:TemplateField HeaderText="ID"
SortExpression="ID"
Visible="False">
<ItemTemplate>
<asp:Label ID="MachineIDLabel"
runat="server"
Text='<%# Bind("ID") %>'
Visible="false"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="MachineIDText"
runat="server"
Text='<%# Bind("ID") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SiteName"
HeaderText="Site Name"
SortExpression="SiteName"
ReadOnly="true" />
<asp:BoundField DataField="Name"
HeaderText="Machine Name"
ReadOnly="true"
SortExpression="Name" />
<asp:TemplateField HeaderText="Machine Type"
SortExpression="MachineType">
<ItemTemplate>
<asp:Label ID="MachineTypeLabel"
runat="server"
Text='<%# Bind("MachineType") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="MachineTypeDropDown"
runat="server"
AppendDataBoundItems="True"
Height="21px"
Width="217px"
DataSourceID="GetMachineType"
DataTextField="Name"
DataValueField="ID">
<asp:ListItem Enabled="true"
Text="Select a Machine Type."
Value="empty">
</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Machine Model" SortExpression="MachineModel">
<ItemTemplate>
<asp:Label ID="MachineModelLabel"
runat="server"
Text='<%# Bind("MachineModel") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="MachineModelDropDown"
runat="server"
AppendDataBoundItems="True"
Height="21px" Width="217px"
DataSourceID="GetMachineModel"
DataTextField="Name"
DataValueField="ID">
<asp:ListItem Enabled="true"
Text="Select a Machine Model."
Value="empty">
</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button"
ShowEditButton="True"
CausesValidation="false" >
<ItemStyle HorizontalAlign="Center"
Wrap="True" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="Transparent" />
<PagerStyle BackColor="Transparent"
ForeColor="Black"
HorizontalAlign="Left" />
<SelectedRowStyle BackColor="Transparent"
Font-Bold="True"
ForeColor="White" />
<HeaderStyle BackColor="Black"
Font-Bold="True"
ForeColor="White"
HorizontalAlign="Center" />
</asp:GridView>
非常感谢您的帮助或建议
谢谢您是否尝试在gridview中设置
EnableViewState=“True”
在没有视图状态启用的情况下进行回发时,asp可能不知道回发时dropdownlist的状态是什么。请尝试将gridview的DataKeyNames属性设置为正在填充gridview的表的id,例如
<asp:GridView ID="gvEmployees" runat="server" DataKeyNames="EmployeeId" ...
我有,但当我这样做时,它会在进入编辑模式并尝试更新或取消时抛出加载viewstate失败错误。它提到要加载的控件树必须与用于保存初始ViewState的控件树匹配,如果仅在以下情况下绑定数据,则可能!Page.IsPostback,并保持viewstate处于启用状态?不,启用enableviewstate后,它会抛出该错误,甚至根本不进入代码以进行更新和取消抱歉,我无法提供更多帮助。听起来像是页面生命周期的一些问题,所以可能值得一看。祝你好运。好吧,我试过了,但似乎没有什么明显的效果,除非我做错了什么。我将datakeynames=设置为要处理的表的主键
/// <summary>
/// Handles the Click event of the update button under edit in the gridview control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
protected void GridViewHolder_Updating(object sender, GridViewUpdateEventArgs e)
{
logger.Debug("Entering GridviewHolder_Updating");
int machineid;
string machineid1;
string machineTypeid;
string machineModelid;
//retrieve and set the data
GridViewHolder.EditIndex = e.RowIndex;
try
{
GridViewRow row = (GridViewRow)GridViewHolder.Rows[e.RowIndex];
TextBox mID = row.FindControl("MachineIDText") as TextBox;
DropDownList mType = row.FindControl("MachineTypeDropDown") as DropDownList;
DropDownList mModel = row.FindControl("MachineModelDropDown") as DropDownList;
machineid1 = mID.Text;
machineid = Convert.ToInt32(machineid1);
machineTypeid = mType.SelectedValue;
machineModelid = mModel.SelectedValue;
try
{
if (machineTypeid != "empty" || machineModelid != "empty")
{
if (machineTypeid != "empty")
{
inputsService.UpdateMachineTypes(machineid, machineTypeid);
}
if (machineModelid != "empty")
{
inputsService.UpdateMachineModels(machineid, machineModelid);
}
UpdateSucceed.Visible = true;
logger.Debug("Updating - Database successfully updated!");
}
else
{
UpdateFail.Visible = true;
logger.Debug("Updating - Database had no data selected to be updated.");
}
}
catch (Exception ex)
{
logger.ErrorFormat("Updating - Failed to update the table, ex = {0}", ex);
}
}
catch (Exception ex)
{
logger.ErrorFormat("Updating.gathering page controls - Failed to update the table, ex = {0}", ex);
}
logger.Debug("Leaving GridViewHolder_Updating");
}
/// <summary>
/// Handles the Click event of the cancel button under edit in the gridview control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
protected void GridViewHolder_Canceling(object sender, GridViewCancelEditEventArgs e)
{
logger.Debug("Entering GridViewHolder_Canceling");
//reset the edit index
GridViewHolder.EditIndex = -1;
//Bind data to GridViewHolder
BindData();
logger.Debug("Leaving GridViewHolder_Canceling");
}
/// <summary>
/// Handles the Click event of the cancel button under edit in the gridview control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
protected void GridViewHolder_Editing(object sender, GridViewEditEventArgs e)
{
logger.Debug("Entering GridViewHolder_Editing");
//set the edit index to a new value
GridViewHolder.EditIndex = e.NewEditIndex;
//Bind data to gridviewholder
BindData();
logger.Debug("Leaving GridViewHolder_Editing");
}
private void BindData()
{
logger.Debug("Entering DataBind");
GridViewHolder.DataSource = Session["MachineTable"];
GridViewHolder.DataBind();
logger.Debug("Leaving DataBind");
}
<asp:GridView ID="gvEmployees" runat="server" DataKeyNames="EmployeeId" ...