2

Gridview update is not happening after I edit it. Used breakpoints and checked, its showing the same existing values which is there before editing. I am not getting any kind of error. Have used Store Procedure to update the Gridview. Please go through the code and help me sort out this problem.

aspx code

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

stored procedure

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;
Suraj
  • 494
  • 3
  • 10
  • 23

1 Answers1

3

GrdGetComments(); is running in your Page_Load, which binds the gridview again after editing (without saving). This needs to be in the (!IsPostBack).

Page life cycle indicates that Page_Load will always run before any other button clicks: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.90).aspx

You need to bind your gridview inside the if (!IsPostBack).

The stored procedure also needs a return value, for example adding a return to the end will allow you to grab this within your C# code.

FirstCape
  • 639
  • 13
  • 30
  • It still needs removing however, its being bound in a `!IsPostBack` and outside of that if statement, which isn't that efficient. – FirstCape Dec 10 '13 at 13:35
  • 2
    thnks again u wer right... i thought i had binded it in postback n removed it frm page load but after looking at the code again got to know wat was the mistake.... im getting updated values in grid view but data isnt storing in db – Suraj Dec 10 '13 at 13:46
  • No problem, easy mistake to make with wads of code that have multiple references to multiple `void`s. As a reference always good to keep them in a `!IsPostBack` and then remove as and when necessary. – FirstCape Dec 10 '13 at 13:49
  • sure... can u look for te other prblm... data isnt getting stored in db nw... gettin msg sayin failed to save comment...applied breakpoint n checked ..no error prblm in updategvData code – Suraj Dec 10 '13 at 13:52
  • No problem, I've looked at your stored procedure and seen that it doesn't return a value have a look here for some tips: http://stackoverflow.com/questions/6210027/c-sharp-calling-sql-server-stored-procedure-with-return-value – FirstCape Dec 10 '13 at 14:46
  • didnt get wats d prbm with tht bro – Suraj Dec 11 '13 at 11:22