通过代码在GridView中更新项目

时间:2011-04-08 16:01:07

标签: c# asp.net linq-to-sql gridview

我有一个GV,我想在其中更新我的项目。我没有使用LDS或任何因为我更新存储在多个数据库中的项目。

以下是我的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>

以下是我一直在尝试的代码,但我无法在我的变量中获取更新的TEXT:

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



    }

2 个答案:

答案 0 :(得分:2)

两个想法: 首先,您可以使用模板字段作为列和&amp;命名控件     持有你的数据。然后可以按如下方式检索这些控件的内容:((TextBox)e.Row.FindControl("TextBoxProductName")).Text

模板看起来像这样:

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

另请注意,由于您手动数据绑定gridview,因此在编辑按钮触发的RowEditing(非RowUpdating)事件中,必须设置gridview的编辑索引。尝试:

gvShowComm.EditIndex = e.Row.RowIndex;

或者,第二,你可以拥有多个数据键     网格视图。尝试类似的东西:     DataKeyNames="Product_ID,Product_Name,Product_Price"

然后可以按如下方式检索这些值:

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

我应该注意到DataKeys只是设计用于保存db主键。将它们用于其他任何事情都是一种破解。也就是说,当我需要为每一行存储一些信息时,偶尔需要它,但我不希望它对用户可见。

最后一点,不要将数据绑定放在页面加载中,除非你把它放在一个只触发初始页面加载而不是每次回发的条件中。例如:if(!IsPostback)......

答案 1 :(得分:1)

如果在GridViews标记中添加属性DataKeyNames="Product_ID",则会在RowUpdating上获得Product_ID的值,

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