-9

我一直在尝试将字符串值从一种方法传递到另一种方法。这是我的两种方法。

方法1-

public void listBox1_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count > 0)
    {
        var c_id = (e.AddedItems[0] as Foodlist).C_ID;
        string listboxid = c_id.ToString();
    }
}

我想要第二种方法中的字符串 listboxid 值,以便我可以使用它进行比较。
方法2-

public void deletemyfood()
{
    using (FoodDataContext context = new FoodDataContext(Con_String))
    {
        string listboxindex = listboxid;
        IQueryable<FoodViewModel> foodQuery = from c in context.FoodTable where c.C_ID.ToString() == listboxindex select c;
        ....
    }
}

有什么想法或建议吗?

4

1 回答 1

2

这是一个关于如何使用返回值和参数的简单示例:

class Program
{
    static void Main(string[] args)
    {
        var result = Method1("Test");
    }

   static string Method1(string input)
   {
       return string.Format("I got this input: {0}", input);
   }
}

在此示例中,该方法Method1接受一个字符串参数,然后返回一个字符串。

在您的情况下,您可能希望将方法签名更改为DeleteMyFood

public void DeleteMyFood(string foodId)

但是,如果您想要某种结果,也知道该方法何时成功或不成功,您可能还希望从该方法返回一个值。这可以通过再次修改方法签名来完成:

public bool DeleteMyFood(string foodId)

如果我根据您的评论正确理解,您希望将事件处理程序更改为:

public void listBox1_SelectionChanged(object sender,
                                    System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count > 0)
    {
        var c_id = (e.AddedItems[0] as Foodlist).C_ID;
        string listboxid = c_id.ToString();
        DeleteMyFood(listboxid);
    }
}

这要求该方法DeleteMyFood接受字符串类型的参数,因此我们也需要更改它:

public void deletemyfood(string foodId)
{
    using (FoodDataContext context = new FoodDataContext(Con_String))
    {
        string listboxindex = listboxid;
        IQueryable<FoodViewModel> foodQuery = from c in context.FoodTable where c.C_ID.ToString() == foodId select c;
        // .. rest of code here ..
    }
}
于 2012-07-03T14:01:28.643 回答