C#-获得特定值或选定的微调器项目

时间:2018-12-20 22:06:47

标签: c# spinner

我有问题。

我与一些客户创建了一个微调器。微调器是根据包含4列的列表构建的:Id,名称,年龄,性别。在微调器中,我创建了以下项目:
编号:1-名称:John-年龄:46-性别:男性
ID:2-姓名:Micheal-年龄:32-性别:男

等等

现在我想要的是获取所选项目的ID,但是我无法弄清楚,因为我创建了一个自定义项目字符串。因此,当我需要输入时,我当然会得到整个字符串。我怎么只能获取字符串的ID并切断以下内容:“ Id:=>-名称:...-年龄:...-性别:...” 剩下的是作为 Int 的ID吗?

private void CustomerSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
    Spinner spinner = (Spinner)sender;
    SelectedSpinnerCustomer = spinner.GetItemAtPosition(e.Position).ToString();
    LoadCustomerInfo(SelectedSpinnerCustomer);
}

为了清楚起见,我希望 SelectedSpinnerCustomer 是一个整数。我该怎么办?

3 个答案:

答案 0 :(得分:1)

最好的方法是创建一个自定义的Spinner类,该类继承常规的spinner类并包含您的所有四个属性

public class MySpinner : Spinner
{
   public int Id { get; set; }
   public int Age { get; set; }
   public string Name { get; set; }
   public string Gender { get; set; }
} 

然后参加活动

private void CustomerSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
    MySpinner spinner = sender as MySpinner;
    int SelectedSpinnerCustomer = spinner.Id;
    int age = spinner.Age;
    string name = spinner.Name;
    string gender = spinner.Gender;
}

答案 1 :(得分:1)

您可以在string类中使用几种不同的方法。这是一个经过简化的方法,并使用了多种字符串方法。

//Save the string in a local variable with a short name for better readability
string str = spinner.GetItemAtPosition(e.Position).ToString();

//Split the string by the underscores ('-')
string[] splitted = str.Split("-");
//Now you have a string array with all the values by themselves
//We know that ID is the first element in the array since your string starts with the ID
//So save it in a new string
string idStr = splitted[0];
//idStr is now "id: x "
//Remove the spaces by replacing them with nothing
idStr = idStr.Replace(" ", "");
//idStr is now "id:x"
//To get only 'x' we need to remove "id:" which can be done in multiple ways
//In this example I will use String.Remove() method
//Start at index 0 and remove 3 characters. This will remove "id:" from "id:x"
idStr = idStr.Remove(0, 3);
//Now idStr is "x" which is an integer, so we can just parse it
int id = int.Parse(idStr);
//Now you have the id as an integer!

答案 2 :(得分:0)

您可以尝试这样的事情:

var digits = selectedCustomer.SkipWhile(c => !Char.IsDigit(c))
    .TakeWhile(Char.IsDigit)
    .ToArray();

var idstring = new string(digits);
int selectedCustomerId = int.Parse(idstring);