SqlDataSource Gridview не обновляется, но и не падает

 <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>

Выше мой код. Все работает за исключением раздела обновления. Не падает, ничего не делает. В этом проблема. Новые значения отмечаются в базе данных. Приведенный ниже код представляет собой хранимую процедуру

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

Любые предложения будут ценны. Спасибо. Кроме того, при попытке обновить обязательные валидаторы полей для текстовых полей вверху срабатывают, которые используются для вставки. Не уверен, почему это происходит.

Код позади:

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();
  }

Теперь получаю следующую ошибку:

Строка 93: dt.Rows[row.DataItemIndex]["MenuId"] = ((TextBox)(row.Cells[1].Controls[0])).Text


person user2891487    schedule 21.02.2014    source источник
comment
Опубликуйте GridView1_RowUpdate, а также любые другие методы, вызываемые во время обновления.   -  person James    schedule 21.02.2014
comment
Проблема в том, что вы на самом деле ничего не делаете, когда происходит обновление. Все, что он делает, это проверяет, не возникает ли ошибка. Как только вы добавите команды обновления, это должно работать.   -  person James    schedule 21.02.2014


Ответы (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();
}
person James    schedule 21.02.2014