RG-3
RG-3

Reputation: 6188

Updating Items in GridView through Code

I have a GV in which I want to Update my items. I am not using LDS or anything coz I m updating items which are stored in multiple databases.

Here is the markup of my GV:

<asp:GridView runat="server" Height="233px" Width="602px" ID ="gvShowComm" 
        CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing = "gvShowComm_RowEditing" 
        OnRowUpdating = "gvShowComm_RowUpdating" 
        OnRowCancelingEdit = "gvShowComm_RowCancelingEdit">

    <Columns>
        <asp:CommandField ShowCancelButton="True" ShowEditButton="True" />

     <asp:TemplateField HeaderText = "Product ID">
         <EditItemTemplate>
         <asp:TextBox ID = "ProductName" runat = "server" Text ='<%# Bind("Product_ID") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "ProductName" runat = "server" Text ='<%# Bind("Product_ID") %>'/>
         </ItemTemplate>
     </asp:TemplateField>


     <asp:TemplateField HeaderText = "Plan Name">
         <EditItemTemplate>
         <asp:TextBox ID = "PlanName" runat = "server" Text ='<%# Bind("PlanName") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "PlanName" runat = "server" Text ='<%# Bind("PlanName") %>'/>
         </ItemTemplate>
     </asp:TemplateField>

     <asp:TemplateField HeaderText = "1st Yr Comm">
         <EditItemTemplate>
         <asp:TextBox ID = "HiComm" runat = "server" Text ='<%# Bind("HiCommissionOld") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "HiComm" runat = "server" Text ='<%# Bind("HiCommissionOld") %>'/>
         </ItemTemplate>
     </asp:TemplateField>

     <asp:TemplateField HeaderText = "2nd Yr Comm">
         <EditItemTemplate>
         <asp:TextBox ID = "LowComm" runat = "server" Text ='<%# Bind("LowCommissionOld") %>'/>
         </EditItemTemplate>
         <ItemTemplate>
         <asp:Label ID = "LowComm" runat = "server" Text ='<%# Bind("LowCommissionOld") %>'/>
         </ItemTemplate>
     </asp:TemplateField>

    </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" /> 
</asp:GridView>

And here is code I've been trying but I cant able to get the updated TEXT in my 's' variable:

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["EntitySelected"] == null)
        {
            MessageBox.Show("Please Select an Entity first!");
            Response.Redirect("~/FrontEnd/AgentList.aspx");
        }

        int getEntity = Int16.Parse(Session["EntitySelected"].ToString());
        this.Label3.Text = "You Selected Entity: " + (string)Session["EntitySelected"];

        dbWebEnrollDataContext dt1 = new dbWebEnrollDataContext(); //This has PlanName!
        CommissionsV2DataContext cv1 = new CommissionsV2DataContext(); //Entity_Product_Point
        var td = from s in GetEntity()
                 join r in GetPlanName() on s.Product_ID equals r.Product_ID
                 where s.Entity_ID == getEntity
                 select new
                 {
                     s.Product_ID,
                     r.PlanName,
                     s.HiCommissionOld,
                     s.LowCommissionOld


                 };
        gvShowComm.DataSource = td;
        gvShowComm.DataBind();
    }

    static IEnumerable<Entity_Product_Point> GetEntity()
    {
        var context = new CommissionsV2DataContext();
        return (from t in context.Entity_Product_Points select t).AsQueryable();
    }

    static IEnumerable<PlanMaster> GetPlanName()
    {
        var context = new dbWebEnrollDataContext();
        return (from t in context.PlanMasters select t).AsQueryable();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {


            if (ddlPlan.SelectedValue != null && tb1stYr.Text != "" && tbMaximum.Text != "" && tbRecurring.Text != "")
            {
                //Accessing Variables and defining them.
                using (dbWebEnrollDataContext dt = new dbWebEnrollDataContext())
                    try
                    {
                        int getEntity = Int16.Parse(Session["EntitySelected"].ToString());

                        var productName = ddlPlan.SelectedValue.ToString();

                        decimal firststYrComp = Int16.Parse(tb1stYr.Text.ToString());
                        decimal recurringComp = Int16.Parse(tbRecurring.Text.ToString());
                        decimal maximumPercent = Int16.Parse(tbMaximum.Text.ToString());

                        //Pulling the Product_ID from the PlanMaster Table from WebEnroll DB!

                        //var tr = dt.PlanMasters.First(s => s.PlanName == productName);

                        var tr = from s in dt.PlanMasters
                                 where s.PlanName == productName
                                 select s.Product_ID;

                        decimal finalFirstYrComp = decimal.Round((firststYrComp / maximumPercent), 3);
                        decimal finalRecurringComp = decimal.Round((recurringComp / maximumPercent), 3);

                        //Updating the Table: Entity_Product_Points in CommissionsV2 DB.
                        CommissionsV2DataContext cv = new CommissionsV2DataContext();
                        Entity_Product_Point ev = new Entity_Product_Point();
                        ev.Entity_ID = getEntity;
                        ev.Product_ID = tr.First();
                        ev.HiCommissionOld = (double)firststYrComp;
                        ev.LowCommissionOld = (double)recurringComp;
                        ev.HiCommission = (double)finalFirstYrComp * 100;
                        ev.LowCommission = (double)finalRecurringComp * 100;
                        ev.DateCreated = System.DateTime.Now;
                        cv.Entity_Product_Points.InsertOnSubmit(ev);
                        cv.SubmitChanges();

                        var td = from s in GetEntity()
                                 join r in GetPlanName() on s.Product_ID equals r.Product_ID
                                 where s.Entity_ID == getEntity
                                 select new
                                 {
                                     s.Product_ID,
                                     r.PlanName,
                                     s.HiCommissionOld,
                                     s.LowCommissionOld


                                 };

                        gvShowComm.DataSource = td;
                        gvShowComm.DataBind();

                    }

                    catch (Exception err)
                    {
                        MessageBox.Show("" + err);
                    }
            }

            else
            {
                MessageBox.Show("Please Enter Entry for the textboxes!");
            }

            tb1stYr.Text = "";
            tbMaximum.Text = "";
            tbRecurring.Text = "";
            ddlPlan.SelectedIndex = 0;
        }


    protected void gvShowComm_RowEditing(object sender, GridViewEditEventArgs e) 
    {
        gvShowComm.EditIndex = e.NewEditIndex;
        gvShowComm.DataBind();

    }

    protected void gvShowComm_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvShowComm.EditIndex = -1;
        gvShowComm.DataBind();
    }

    protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        System.Web.UI.WebControls.TextBox myBox = gvShowComm.Rows[e.RowIndex].FindControl("PlanName") as System.Web.UI.WebControls.TextBox;
        string s = myBox.Text;
        gvShowComm.DataBind();
    }



    }

Upvotes: 0

Views: 2259

Answers (2)

Joe Schrag
Joe Schrag

Reputation: 865

Two ideas: First, you can use Template Fields for your columns & name the control holding your data. The contents of those controls can then be retrieved as follows: ((TextBox)e.Row.FindControl("TextBoxProductName")).Text

The template would look something like this:

    <asp:TemplateField HeaderText="Product Name">
        <EditItemTemplate>
            <asp:TextBox ID="TextBoxProductName" runat="server" Text='<%# Bind("Product_Name") %>'/>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Label ID="LabelProductName" runat="server" Text='<%# Bind("Product_Name") %>'/>
        </ItemTemplate>
    </asp:TemplateField>

Note also that because you are databinding the gridview manually, in the RowEditing (Not the RowUpdating) event fired by the edit button, you must set the gridview's edit index. Try:

gvShowComm.EditIndex = e.Row.RowIndex;

Or, second, you can have more than one datakey in a gridview. Try something like: DataKeyNames="Product_ID,Product_Name,Product_Price"

Those values can then be retrieved as follows:

gvShowComm.DataKeys[e.RowIndex]["Product_Name"]

I should note that DataKeys are only really designed to hold db primary keys. Using them for anything else is a hack. That said, I've had need for it occasionally when I need to store some piece of information for each row, but I don't want it visible to the user.

A final note, don't put the databinding in the page load unless you are putting it inside a conditional that only fires on initial page load, not every postback. Ex: if(!IsPostback) ...

Upvotes: 2

codeandcloud
codeandcloud

Reputation: 55333

If you add the property DataKeyNames="Product_ID" in the GridViews Markup, you will get the value of Product_ID on RowUpdating as,

var keyValue = gvShowComm.DataKeys[e.RowIndex].Value;
int product = Convert.ToInt32(keyValue);

Upvotes: 1

Related Questions