gridview中的行更新无效

时间:2013-12-10 13:02:52

标签: c# asp.net sql-server-2008 stored-procedures gridview

编辑后,Gridview更新没有发生。使用了断点并进行了检查,它显示了编辑前存在的相同现有值。我没有收到任何错误。已使用Store Procedure更新Gridview。请仔细阅读代码并帮我解决这个问题。

aspx代码

<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" 
              OnRowEditing="gvData_RowEditing" 
              OnRowDataBound="gvData_RowCreated" 
              OnRowCreated="gvData_RowCreated" 
              OnRowCancelingEdit="gvData_RowCancelingEdit"
              OnRowUpdating="gvData_RowUpdating" 
              Style="text-align: center; margin-left: 0px;" Height="160px" 
              Width="657px" BackColor="#DEBA84" BorderColor="#DEBA84" 
              orderStyle="None" BorderWidth="0px" CellPadding="3" CellSpacing="2"
              DataKeyNames="BtnID" Font-Names="Calibri" ForeColor="#CC3300"  
              EmptyDataText="No Records Found!!!" 
              CaptionAlign="Left" HorizontalAlign="Left"
>
    <AlternatingRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" BorderStyle="None" />
    <Columns>
        <asp:TemplateField HeaderText="BtnID" >
            <ItemTemplate>
                <asp:Label ID="lblBtnID" runat="server"  ForeColor="#003366"
                        Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
                        Text='<%#Eval("BtnID") %>'> </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="LogdInUsername" >
            <ItemTemplate>
                <asp:Label ID="lblLogdInUsername" runat="server"  ForeColor="#003366"
                        Font-Names="Calibri" Font-Size="Small" Height="24px" Width="20px"
                        Text='<%#Eval("LogdInUsername") %>'> </asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Year">
            <ItemTemplate>
                <asp:Label ID="lblYear" runat="server"  ForeColor="#003366"
                    Font-Names="Calibri" Font-Size="Small" Height="24px" Text='<%# Eval("Year") %>' Width="20px"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Month">
            <ItemTemplate>
                <asp:Label ID="lblMonth" runat="server"  ForeColor="#003366"
                     Font-Names="Calibri" Font-Size="Small" Text='<%# Eval("Month") %>' Height="24px" Width="20px"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Comments">
            <ItemTemplate>
                <asp:Label ID="lblComments" runat="server"  
                    ForeColor="#003366"  Font-Names="Calibri" Text='<%# Eval("Comments") %>' Font-Size="Small" Height="24px"
                    Width="20px" ></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TxtComments" runat="server" 
                     Width="300px" Text='<%# Bind("Comments") %>' ></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Action">
            <ItemTemplate>
                <asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
                 <asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" 
        BorderStyle="None" />
    <EmptyDataRowStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
    <HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" HorizontalAlign="Left" 
        VerticalAlign="Middle" Wrap="False" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" 
        HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" HorizontalAlign="Left" 
        VerticalAlign="Middle" Wrap="False" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>

cs code

protected void Page_Load(object sender, EventArgs e)
{
    DTO objc = new DTO();

    string str = Environment.UserName;

    GrdGetComments();

    if (!IsPostBack)
    {
        GetYear();
        GetMonth();
        GrdGetComments();

        UserPrincipal up1 = GetUserPrincipal(str);
        Session["Username"] = str;
        Session["Name"] = up1.Name;

        LblName.Text = Session["Username"].ToString();
        objc.Name = LblName.Text;

        LblLogdInUsername.Text = Session["Name"].ToString();
        objc.LogdInUsername = LblLogdInUsername.Text;

        LblDateTime.Text = DateTime.Now.ToString();

        LblCompany.Text = "";
        objc.Company = LblCompany.Text;

    }
}


public static UserPrincipal GetUserPrincipal(String userName)
{
    UserPrincipal up = null;

    PrincipalContext context = new PrincipalContext(ContextType.Domain);
    up = UserPrincipal.FindByIdentity(context, userName);

    if (up == null)
    {
        context = new PrincipalContext(ContextType.Machine);
        up = UserPrincipal.FindByIdentity(context, userName);
    }

    if (up == null)
        throw new Exception("Unable to get user from Domain or Machine context.");

    return up;

}

protected void GetYear()
{
    DTO objc = new DTO();
    {
        DrpForYear.DataSource = obj.GetYear();
        DrpForYear.DataTextField = "Year";
        DrpForYear.DataBind();
    }
}

protected void GetMonth()
{
    DTO objc = new DTO();
    {
        DrpForMonth.DataSource = obj.GetMonth(); ;
        DrpForMonth.DataTextField = "Month";
        DrpForMonth.DataBind();
    }
}

public void GrdGetComments()
{
    DTO objc = new DTO();
    {
        objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
        DataSet GrdVC = obj.GetButtonComment(objc);
        DataView GrdViewC = new DataView();
        GrdViewC.Table = GrdVC.Tables[0];
        gvData.DataSource = GrdViewC;
        gvData.DataBind();
    }
}

protected void BtnSave_Click(object sender, EventArgs e)
{
    DTO objc = new DTO();

    int Flag = 0;

    LblLogdInUsername.Text = Session["Username"].ToString();
    objc.LogdInUsername = LblLogdInUsername.Text;
    objc.DateTime = DateTime.Now;
    objc.Comments = TxtComments.Text;
    objc.Company = LblCompany.Text;

    LblName.Text = Session["Name"].ToString();
    objc.Name = LblName.Text;
    objc.Year = DrpForYear.SelectedItem.Text;
    objc.Month = DrpForMonth.SelectedItem.Text;
    objc.ViewPreference = RadView.SelectedItem.Text;

    int X = obj.InsertButtonComment(objc);

    if (X >= 0)
    {
        Flag = 1;
    }
    else
    {
        Flag = 0;
    }

    if (Flag == 1)
    {
        LblSuccess.Visible = true;
        LblSuccess.Text = "Comment Saved";
    }
    else
    {
        LblErr.Visible = true;
        LblErr.Text = "Failed To Save Comment!!!";
    }

    objc.LogdInUsername = Convert.ToString(Session["LogdInUsername"]);
    DataSet GrdVC = obj.GetButtonComment(objc);
    DataView GrdViewC = new DataView();
    GrdViewC.Table = GrdVC.Tables[0];
    gvData.DataSource = GrdViewC;
    gvData.DataBind();

    TxtComments.Text = "";
    DrpForYear.ClearSelection();
    DrpForMonth.ClearSelection();
    RadView.Text = "";
}

protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvData.EditIndex = e.NewEditIndex;
    GrdGetComments();
}

protected void gvData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvData.EditIndex = -1;
    GrdGetComments();

}

protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    DTO objc = new DTO();

    Label lblBtnID = (Label)gvData.Rows[e.RowIndex].FindControl("lblBtnID");
    Label lblLogdInUsername = (Label)gvData.Rows[e.RowIndex].FindControl("lblLogdInUsername");
    Label lblYear = (Label)gvData.Rows[e.RowIndex].FindControl("lblYear");
    Label lblMonth = (Label)gvData.Rows[e.RowIndex].FindControl("lblMonth");
    Label lblComments = (Label)gvData.Rows[e.RowIndex].FindControl("lblComments");
    TextBox txtComments = (TextBox)gvData.Rows[e.RowIndex].FindControl("TxtComments");

    LblLogdInUsername.Text = Session["Username"].ToString();
    objc.LogdInUsername = LblLogdInUsername.Text;
    objc.Comments = TxtComments.Text;
    objc.BtnID = Convert.ToInt32(Session["BtnID"]);

    int Flag = 0;

    int X = obj.UpdategvData(objc);
    {
        if (X >= 0)
        {
            Flag = 1;
        }
        else
        {
            Flag = 0;
        }
    }

    if (Flag == 1)
    {
        LblSuccss.Visible = true;
        LblSuccss.Text = "Comment Updated";
    }
    else
    {
        LblErrr.Visible = true;
        LblErrr.Text = "Failed To Update Comment!!!";
    }
}

public int UpdategvData(InLogDTO b)
    {
        DBAccess db = new DBAccess();
        SqlParameter objParam = new SqlParameter("@LogdInUsername", b.LogdInUsername);
        objParam.Direction = ParameterDirection.Input;
        objParam.Size = 50;

        db.Parameters.Add(new SqlParameter("@Comments", b.Comments));
        db.Parameters.Add(new SqlParameter("@BtnID", b.BtnID));
        db.Parameters.Add(objParam);

        int retval = db.ExecuteNonQuery("UpdategvData");

        if (retval >= 1)
        {
            int i = 0;
            return i;
        }
        else
        {
            return -1;
        }
    }

存储过程

ALTER PROCEDURE [dbo].[UpdategvData]
    @LogdInUsername nvarchar(50) ,
    @Comments nvarchar(50),
    @BtnID int
AS
    Update dbo.Button_Comments
        Set Comments = @Comments
        Where LogdInUsername = @LogdInUsername and ViewPreference = 'Public' and 
        Comments  = @Comments and BtnID = @BtnID;

1 个答案:

答案 0 :(得分:3)

GrdGetComments();正在您的Page_Load中运行,它会在编辑后再次绑定gridview(不保存)。这需要在(!IsPostBack)

页面生命周期表示Page_Load将始终在任何其他按钮点击之前运行: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.90).aspx

您需要在gridview内绑定if (!IsPostBack)

存储过程还需要一个返回值,例如在末尾添加return将允许您在C#代码中获取它。

相关问题