2014-02-21 5 views
0
<label>Date</label> 
<asp:TextBox ID="txtDate" runat="server" CssClass="entry"></asp:TextBox> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="validator" 
    ErrorMessage="A date is required." ControlToValidate="txtDate"></asp:RequiredFieldValidator> 
<asp:CompareValidator ID="dateValidator" CssClass="validator" runat="server" Type="Date" Operator="DataTypeCheck" ControlToValidate="txtDate" 
    ErrorMessage="Please enter a valid date"></asp:CompareValidator> 
<br /> 



<label>Description</label> 
<asp:TextBox ID="txtMealDescription" runat="server" CssClass="entry" Width="500px"></asp:TextBox> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" CssClass="validator" 
ErrorMessage="Please describe the meal." ControlToValidate="txtMealDescription"></asp:RequiredFieldValidator> 
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Meal description cannot be longer than 250 characters. Please try again." 
    ControlToValidate="txtMealDescription" OnServerValidate="CustomValidator1_ServerValidate" CssClass="validator"></asp:CustomValidator> 
<br /> 




<label>Type</label> 
<asp:DropDownList ID="ddlMealType" runat="server" CssClass="entry" > 
    <asp:ListItem Text="Breakfast" Value="Breakfast"></asp:ListItem> 
    <asp:ListItem Text="Dinner" Value="Dinner"></asp:ListItem> 
</asp:DropDownList> 
<br /> 
<asp:Button ID="btnAdd" runat="server" Text="Add New Meal" OnClick="btnAdd_Click" /> 
<br /> 
<br /> 
<asp:Label ID="lblError" runat="server" EnableViewState="False" CssClass="error"></asp:Label> 
<asp:GridView ID="GridView1" 
    runat="server" 
    CellPadding="4" 
    DataSourceID="SqlDataSource1" 
    AutoGenerateColumns="False" 
    DataKeyNames="MealID,Date,MealDescription,MealType" 
    OnRowUpdated="GridView1_RowUpdate" 
    OnRowDeleted="GridView1_RowDelete" ForeColor="#333333" GridLines="None"> 

    <EditRowStyle BackColor="#2461BF" /> 

    <FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" /> 
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> 
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> 
    <RowStyle BackColor="#EFF3FB" /> 
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> 
    <SortedAscendingCellStyle BackColor="#F5F7FB" /> 
    <SortedAscendingHeaderStyle BackColor="#6D95E1" /> 
    <SortedDescendingCellStyle BackColor="#E9EBEF" /> 
    <SortedDescendingHeaderStyle BackColor="#4870BE" /> 

    <AlternatingRowStyle BackColor="White" /> 

    <Columns> 

    <asp:BoundField DataField="MealID" HeaderText="ID" Visible="false" /> 

    <asp:TemplateField HeaderText="Date"> 
     <ItemTemplate> 
     <asp:Label ID="lblGridDate" runat="server" Text='<%# Bind("Date", "{0:M/dd/yyy}") %>' Width="75px"></asp:Label> 
     </ItemTemplate> 
     <EditItemTemplate> 
     <asp:TextBox ID="txtGridDate" runat="server" Text='<%# Bind("Date", "{0:M/dd/yyy}") %>' Width="75px"></asp:TextBox> 
     </EditItemTemplate> 
    </asp:TemplateField> 

    <asp:TemplateField HeaderText="Meal Description"> 
     <ItemTemplate> 
     <asp:Label ID="lblGridMealDescription" runat="server" Text='<%# Bind("MealDescription") %>' Width="500px"></asp:Label> 
     </ItemTemplate> 
     <EditItemTemplate> 
     <asp:TextBox ID="txtGridMealDescription" runat="server" Text='<%# Bind("MealDescription") %>' Width="500px"></asp:TextBox> 
     </EditItemTemplate> 
    </asp:TemplateField> 

    <asp:TemplateField HeaderText="Meal Type"> 
     <ItemTemplate> 
     <asp:Label ID="lblGridMealType" runat="server" Text='<%# Bind("MealType") %>' Width="100px"></asp:Label> 
     </ItemTemplate> 
     <EditItemTemplate> 
     <asp:DropDownList ID="ddlGridMealType" runat="server" SelectedValue='<%# Bind("MealType") %>' Width="100px"> 
      <asp:ListItem Text="Breakfast" Value="Breakfast"></asp:ListItem> 
      <asp:ListItem Text="Dinner" Value="Dinner"></asp:ListItem> 
     </asp:DropDownList>    
     </EditItemTemplate> 
    </asp:TemplateField> 

    <asp:CommandField ButtonType="Button" ShowEditButton="true" HeaderText="Edit" ItemStyle-Width="75px" ItemStyle-HorizontalAlign="Center"/> 

    <asp:TemplateField HeaderText="Delete"> 
     <ItemTemplate> 
     <asp:Button ID="btnDelete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this record?');" 
      CommandName="Delete" Text="Delete" Width="50px"></asp:button> 
     </ItemTemplate> 
    </asp:TemplateField> 

    </Columns> 

</asp:GridView> 
<br /> 
<asp:SqlDataSource ID="SqlDataSource1" 
    runat="server" 
    ConnectionString="<%$ ConnectionStrings:CampRandolphMenuTwoConnectionString %>" 
    InsertCommand="sp_ins_MenuItems" InsertCommandType="StoredProcedure" 
    SelectCommand="sp_sel_MenuItems" SelectCommandType="StoredProcedure" 
    UpdateCommand="sp_edit_MenuItems" UpdateCommandType="StoredProcedure" 
    DeleteCommand="sp_del_MenuItems" DeleteCommandType="StoredProcedure"> 
    <InsertParameters> 
    <asp:Parameter Name="Date" DbType="Date" /> 
    <asp:Parameter Name="MealDescription" Type="String" /> 
    <asp:Parameter Name="MealType" Type="String" /> 
    </InsertParameters> 
    <UpdateParameters> 
    <asp:Parameter Name="MealID" Type="Int32" /> 
    <asp:Parameter Name="date" DbType="Date" /> 
    <asp:Parameter Name="MealDescription" Type="String" /> 
    <asp:Parameter Name="MealType" Type="String" /> 
    </UpdateParameters> 
    <DeleteParameters> 
    <asp:Parameter Name="MealID" Type="Int32" /> 
    </DeleteParameters> 
</asp:SqlDataSource> 

위 코드는 내 코드입니다. 모든 것이 업데이트 섹션에서 제외됩니다. 충돌하지 않고 아무 것도하지 않습니다. 그게 문제 야. 새 값은 데이터베이스에서 업데이트 된 메모입니다. 아래 코드는 저장 프로 시저입니다.SqlDataSource Gridview가 업데이트되지 않지만 크래시가 발생하지 않습니다.

ALTER procedure [dbo].[sp_edit_MenuItems] 
@MealID int, 
@date date, 
@MealDescription varchar(250), 
@MealType varchar(10) 
as 
begin 
UPDATE Menu 
SET 
date = @date, 
MealDescription = @MealDescription, 
MealType = @MealType 
WHERE 
(MealID = @MealID) 
END 

모든 의견을 크게 환영 할 것입니다. 고맙습니다. 또한 텍스트 상자에 필요한 필드 유효성 검사기를 업데이트하려고 시도 할 때 삽입에 사용되는 최고 킥을 사용합니다. 그 이유가 확실하지 않습니다. 뒤에

코드 :

행 93 : dt.Rows [row.DataItemIndex] [ "menuId와"] = ((텍스트 상자) (row.Cells [

public partial class EditMenuTwo : System.Web.UI.Page 
{ 
protected void Page_Load(object sender, EventArgs e) 
{ 
ddlMealType.Items.Insert(0, new ListItem(String.Empty, String.Empty)); 
ddlMealType.SelectedIndex = 0; 
} 

protected void btnAdd_Click(object sender, EventArgs e) 
{ 
SqlDataSource1.InsertParameters["Date"].DefaultValue = txtDate.Text; 
SqlDataSource1.InsertParameters["MealDescription"].DefaultValue = txtMealDescription.Text; 
SqlDataSource1.InsertParameters["MealType"].DefaultValue = ddlMealType.Text; 

try 
{ 
    SqlDataSource1.Insert(); 
    txtDate.Text = ""; 
    txtMealDescription.Text = ""; 
    ddlMealType.Text = ""; 
} 
catch (Exception ex) 
{ 
    lblError.Text = "A database error has occcurred. <br /><br />" + 
    "Message: " + ex.Message; 
} 
} 

protected void GridView1_RowUpdate(object sender, GridViewUpdatedEventArgs e) 
{ 
if (e.Exception != null) 
{ 
    lblError.Text = "A database error has occurred.<br /><br />" + 
    "Message: " + e.Exception.Message; 
    e.ExceptionHandled = true; 
    e.KeepInEditMode = true; 
} 
else if (e.AffectedRows == 0) 
{ 
    lblError.Text = "Another user may have updated that category." + 
    "<br />Please try again."; 
} 
} 

protected void GridView1_RowDelete(object sender, GridViewDeletedEventArgs e) 
{ 
if (e.Exception != null) 
{ 
    lblError.Text = "A database error has occurred.<br /><br />" + 
    "Message: " + e.Exception.Message; 
    e.ExceptionHandled = true; 
} 
else if (e.AffectedRows == 0) 
{ 
    lblError.Text = "Another user may have updated that category." + 
    "<br />Please try again."; 
} 
} 


protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) 
{ 
    args.IsValid = (txtMealDescription.Text.Length <= 250); 
} 

} 
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{ 

    DataTable dt = (DataTable)Session["Menu"]; 


    GridViewRow row = GridView1.Rows[e.RowIndex]; 
    dt.Rows[row.DataItemIndex]["MenuId"] = ((TextBox)(row.Cells[1].Controls[0])).Text; 
    dt.Rows[row.DataItemIndex]["Date"] = ((TextBox)(row.Cells[2].Controls[0])).Text; 
    dt.Rows[row.DataItemIndex]["MealDescription"] = ((TextBox)(row.Cells[3].Controls[0])).Text; 
    dt.Rows[row.DataItemIndex]["MealType"] = ((DropDownList)(row.Cells[4].Controls[0])).Text; 


    GridView1.EditIndex = -1; 

    GridView1.DataBind(); 
    } 

이제 다음과 같은 오류를 수신 . 1] .Controls [0])) 텍스트

+0

이 GridView1_RowUpdate을 게시하시기 바랍니다, 플러스 다른 나 thod는 업데이트 중에 호출됩니다. – James

+0

문제는 업데이트가 발생할 때 실제로 아무 것도하지 않는다는 것입니다. 오류가 발생하는지 확인하기 만하면됩니다. 업데이트 명령을 추가하면 제대로 작동합니다. – James

답변

1

업데이트 방법에서 누락 된 것의 예 :

protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e) 
{  
    //Retrieve the table from the session object. 
    DataTable dt = (DataTable)Session["TaskTable"]; 

    //Update the values. 
    GridViewRow row = TaskGridView.Rows[e.RowIndex]; 
    dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text; 
    dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text; 
    dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked; 

    //Reset the edit index. 
    TaskGridView.EditIndex = -1; 

    //Bind data to the GridView control. 
    BindData(); 
} 
관련 문제