그래서 gridview가 포함 된 페이지를 가지고, girdview는 웹 서비스를 통해 objectdatasource에서 데이터를 가져옵니다. itemtemplates와 함께 두 개의 열을 포함합니다. 편집 모드에있을 때 각 템플릿에 대해 edititemtemplates 아래에 저장되는 드롭 다운 목록을 포함합니다.올바르게 gridview를 데이터 바인딩하는 방법은 무엇입니까?
편집 모드이고 업데이트 이벤트가 발생하는 경우를 제외하고 모든 항목이 정상적으로 작동하는 것 같습니다. 내 드롭 다운리스트는 null 참조 오류를 발생시킵니다. 추후 조사를 통해 코드 숨김이 dropdroplists를 찾을 수 없다고 생각하는 것으로 보입니다. 또한 디버거를 파헤 치면 드롭 다운리스트가 존재하지 않는 것처럼 보입니다. 비록 내 페이지에서 드롭 다운리스트가 편집 모드에있을 때 표시되지만 코드 숨김은 해당 컨트롤을 찾을 수 없습니다.
내가 추측하고있는 것은 잘못된 위치에서 gridview를 바인딩하고 있거나 바인딩 자체가 잘못 수행되고 있다는 것입니다.
제가 알고 싶은 것은, 왜 이런 상황이 발생하고 어떻게 해결할 수 있습니까? 제 바인딩을 올바르게하고 있는지 누군가가 알려주면 감사하겠습니다.
아래에는 gridview와 codebehind에 대한 내 코드가 있습니다.
의 GridView :
<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>
코드 숨김 :
Pageload 방법 :
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
logger.Debug("Entering Page_Load");
Boolean loginRequired = true;
// If no login is required set the session variable and proceed to the main page.
string str = ConfigurationManager.AppSettings["i0"] as string;
if (!string.IsNullOrEmpty(str))
{
string flag = MyExtensions.Decrypt(str, true);
if ("false".Equals(flag, StringComparison.InvariantCultureIgnoreCase))
loginRequired = true;
else
{
loginRequired = false;
// User logged in so check the permissions.
UserInfo user = (UserInfo)Session[Constants.LOGGEDINUSER];
if (null == user)
loginRequired = true;
else
{
string groupId = user.GroupId;
if (string.IsNullOrEmpty(groupId))
loginRequired = true;
else if (!"Admins".Equals(user.GroupId) && !"Engineer".Equals(user.GroupId))
loginRequired = true;
}
}
}
if (!Page.IsPostBack)
{
Control ctrl = MyExtensions.FindControlRecursive(this, "CommissioningLoginPanel");
Panel loginPanel = null;
Panel contentPanel = null;
if (null != ctrl)
{
loginPanel = (Panel)ctrl;
ctrl = MyExtensions.FindControlRecursive(this, "CommissioningPanel");
if (null != ctrl)
contentPanel = (Panel)ctrl;
}
if (loginRequired)
{
if (null != loginPanel)
loginPanel.Visible = true;
if (null != contentPanel)
contentPanel.Visible = false;
}
else
{
if (null != loginPanel)
loginPanel.Visible = false;
if (null != contentPanel)
contentPanel.Visible = true;
}
}
BindData();
logger.Debug("Leaving Page_Load");
}
있는 gridview 이벤트 :
/// <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");
}
BindData 방법 :
private void BindData()
{
logger.Debug("Entering DataBind");
GridViewHolder.DataSource = Session["MachineTable"];
GridViewHolder.DataBind();
logger.Debug("Leaving DataBind");
}
어떤 도움이나 제안을 해주시면 대단히 감사하겠습니다.
는 당신에게 감사
내가 가진 예를 들어와있는 gridview를 populationg하는 테이블의 id에있는 gridview의 DataKeyNames 속성을 설정 보시기 바랍니다,하지만 난 그렇게되면 그것은이시 viewstate가 오류를로드하는 데 실패 발생 수 편집 모드로 들어가서 업데이트 또는 취소하려고합니다. 그것은 컨트롤 트리에 대해 뭔가를 언급 초기 제어 상태를 저장하는 데 사용 된 컨트롤 트리 일치해야합니다 – James213
경우에만 경우에만 데이터를 바인딩하는 경우! Page.IsPostback 및 viewstate 계속 사용할 수 있습니까? – plntxt
내가 그걸 해보겠습니다. 감사합니다. – James213