简体   繁体   English

C#代码隐藏控制表单执行

[英]C# Code-behind control form execution

I have a form that I would like to reuse for both adding a new record and editing an existing record. 我有一个要重用的表单,用于添加新记录和编辑现有记录。 I am able to successfully load the page with the relevant data when I select a record from a GridView and I am able to update the db record appropriately. 当我从GridView中选择一条记录时,我能够成功地用相关数据加载页面,并且能够适当地更新数据库记录。 However, my issue is trying to use the form for both executions. 但是,我的问题是试图将表格用于两次执行。 Here is my logic in code behind: (I assign a session variable when I click on the row in GridView and this does work successfully) 这是我背后的代码逻辑:(当我单击GridView中的行时,我分配了一个会话变量,这确实可以正常工作)

protected void Page_Load(object sender, EventArgs e)
{
    resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load

    //Checking to see if session variable has been created
    if (Session["editID"] != null)
    {               
        //Create objects to get recipe data
        dbCRUD db = new dbCRUD();
        Recipe editRecipe = new Recipe();

        //Grabbing session ID and assigning to a variable in order to remove the session variable
        var id = Convert.ToInt32(Session["editID"]);
        Session.Remove("editID");

        //Call method to retrieve db data
        editRecipe = db.SelectRecord(id);

        //Populate results to text boxes
        recordID.Text = id.ToString();
        addName.Text = editRecipe.Name;
        addTypeDDL.SelectedValue = editRecipe.Meal;
        addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
        addCookTime.Text = editRecipe.Cook_Time.ToString();
        addDirections.Text = editRecipe.Directions;

        //Change Button Text
        submitRecord.Visible = false;
        changeRecord.Visible = true;

        //Change Title Text
        addEditTitle.Text = "Edit Recipe";

    }
}

protected void submitRecord_Click(object sender, EventArgs e) 
{
    //Variables for execution results
    var modified = "";
    int returned = 0;

    //Creating the recipe Object to pull the values from the form and 
    //send the recipe object as a parameter to the method containing insert stored procedure
    //depending on Add or Edit
    Recipe recipe = new Recipe();
    recipe.Name = addName.Text;
    recipe.Meal = addTypeDDL.Text;
    recipe.Difficulty = addDifficultyDDL.Text;
    recipe.Cook_Time = int.Parse(addCookTime.Text);
    recipe.Directions = addDirections.Text;

    //Creating object to access insert method
    dbCRUD newRecord = new dbCRUD();

    //Checking to see if the page is loaded for edit or new addition
    if (Session["editID"] != null)
    {
        //If recordID exists, recipe will be passed as to UpdateRecord method
        recipe.Recipe_ID = int.Parse(recordID.Text);
        returned = newRecord.UpdateRecord(recipe);
        modified = "has been edited.";
        Session.Remove("editID");
    }
    else
    {
        //If recordID does not exist, record will be passed to InsertRecord method (new recipe)
        returned = newRecord.InsertRecord(recipe);
        modified = "added";
    }

    //Method returns 0 if successful, 1 if sql error, 2 if other error
    if (returned == 1)
    {
        resultOutput.Text = "There was an sql exception";
        resultOutput.Visible = true;
    }
    else if (returned == 2)
    {
        resultOutput.Text = "There was a non sql exception";
        resultOutput.Visible = true;
    }
    else
    {
        resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
        resultOutput.Visible = true;
    }

}

I have issues on the if(Session["editID"] != null) line - I am always moved to the else logic and the if logic never runs. 我在if(Session [“ editID”]!= null)行上遇到问题-我总是被转移到else逻辑上,而if逻辑永远不会运行。

Here is my click method in the GridView: 这是我在GridView中的click方法:

protected void Grid_Recipe_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = Convert.ToInt32(Grid_Recipe.SelectedDataKey.Value);
    Session["editID"] = index;
    Response.Redirect("addRecord.aspx");
}

My question is how can I control execution during the submitRecord_Click event so that I call the appropriate method. 我的问题是如何在submitRecord_Click事件期间控制执行,以便调用适当的方法。 Thanks! 谢谢!

Have you considered using 您是否考虑过使用

if(Page.IsPostBack)
{
   code here
}

To detect whether you are posting back to the page? 要检测您是否正在回发页面? Then you could check your value of the item. 然后,您可以检查商品的价值。 I see no reason the code shouldn't be in the Session variable - have you tried putting a breakpoint in there to see if the code actually gets in there? 我没有理由不应该将代码放在Session变量中-您是否尝试过在其中放置一个断点以查看代码是否真正到达那里?

Also does your addRecord.aspx just add the record? 您的addRecord.aspx还会添加记录吗? If so, just add the record in this class, but use the PostBack check to see. 如果是这样,只需在该类中添加记录,然后使用PostBack检查即可。 Could you just make sure you are saving in the right context aswell: 您能否确保也在正确的上下文中进行保存:

// Outside of Web Forms page class, use HttpContext.Current.
HttpContext context = HttpContext.Current;
context.Session["editID"] = index;
...
int Id = (string)(context.Session["editID"]);

I was able to figure out my issue - which actually turned into two issues. 我能够弄清楚我的问题-实际上变成了两个问题。 First, I had to put my Page Load logic in a if(!IsPostBack) statement because I could not edit the page. 首先,我不得不将页面加载逻辑放在if(!IsPostBack)语句中,因为我无法编辑页面。 Reason being is I was loading the originally posted data to the form on page load, which executed before my logic. 原因是我正在将最初发布的数据加载到页面加载时的表单上,该表单在执行逻辑之前执行。 Adding the if(!IsPostBack) control statement fixed this issue. 添加if(!IsPostBack)控制语句可解决此问题。 From there, I'm still using a session variable to control code behind logic, only I made sure keep my session variable only between the form and the gridview. 从那里开始,我仍在使用会话变量来控制逻辑背后的代码,只有我确保将会话变量仅保留在表单和gridview之间。 Basically, when the gridview loads and it is not a post back, the session variable is cleared. 基本上,当gridview加载并且不是回发时,将清除会话变量。 This let's me set a new session variable when I click on a row and then the session variable is cleared once I return to the grid to see the results. 这让我们在单击一行时设置一个新的会话变量,然后一旦返回网格以查看结果,便会清除该会话变量。 Thanks for the help! 谢谢您的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM