从另一个文件获取变量的值

时间:2019-06-12 00:11:30

标签: c# asp.net

我有2个文件,在第一个文件中,我有文本框,用户可以在其中输入值。我想采用该值并将其带到另一个文件。在该程序中,我让用户也在文本框中输入一个值。如果他们输入的值高于其他值,则会出现错误。

例如:文件2询问您要吃多少个窃笑器,文件1(询问用户我们有多少个窃笑器)。如果您想吃的东西比您所吃的更多,那么您会得到一个错误。

我不确定如何在其他文件中获取此值。

文件1:

protected void Page_Load(object sender, EventArgs e)
    { 
            //create string and set it equal to the textbox text
            string snickersInventory = txtInventorySnickers.Text;
            //create a int and turn the string into an int
            int stockSnickers = Int32.Parse(snickersInventory);

     }

文件2:

protected void btnSubmit_Click(object sender, EventArgs e)
    {
      //Check to see if the stockSnickers is lower than the amount of Snickers Value
    }

3 个答案:

答案 0 :(得分:0)

我希望这与您感兴趣的东西类似:

/* Program 1 - Save our snicker count to a file */
var snickerInventory = txtInventorySnickers.Text;

// No need to convert to number if you're going to write directly to file.
System.IO.File.WriteAllText(@"c:\snickersInventoryCount.txt", snickerInventory);


/* Program 2 - Try to eat some snickers. */
var howManySnickersToEat = int.Parse(txtInventorySnickers.Text);
var snickersOnHandFileData = System.IO.File.ReadAllText(@"c:\snickersInventoryCount.txt");
var snickersOnHand = int.Parse(snickersOnHandFileData);

if(snickersOnHand < howManySnickersToEat) { /* Do error stuff here */ }

您肯定会在将字符串解析为int时添加错误处理。看一下int.TryParse(),尤其是在使用用户输入的情况下。

基本上,这是简单地写入文件/从文件读取的要旨。如果程序不在同一时间运行,这很好。如果您尝试同时从文件中读取/写入文件,则会遇到问题。

您可能会考虑使用数据库而不是文件来在两个应用程序之间共享信息。

答案 1 :(得分:0)

将File1的Textbox修饰符声明为public。

System.Web.Application.File f = System.Web.Application.["WebForm1"];

在File2中声明以下内容:

protected void btnOn_Click(object sender, EventArgs e)
    {
      var howMany = txt_howManySneakers.text;     // File1
      var EatSneakers = ((WebForm1)f).txtbox1.Text;  // File2

      if (EatSneaker > howMany )
        {
           // DO ERROR
        }
    }

答案 2 :(得分:0)

非常简单,将用户输入的值放在文件1的会话对象中,如下所示

//create string and set it equal to the textbox text
string snickersInventory = txtInventorySnickers.Text;
//create a int and turn the string into an int
int stockSnickers = Int32.Parse(snickersInventory);

Session["stockSnickers"]=stockSnickers;

并在文件2中获得高于以下值的值

if(Session["stockSnickers"] != null)
{
   int stockSnickers = Convert.ToInt32(Session["stockSnickers"]);
   // do something with above value
}

希望对您有帮助。...:)

相关问题