我正在嘗試將資料添加到組合框中,我正在添加一個 ID 和一個名稱,兩者都出現在同一行。我使用 ~ 來分隔名稱和 ID。但是我不知道如何在不添加 ~ 的情況下將這些值放入組合框中
try
{
StreamReader sr = new StreamReader("nameForSkiTimes.txt");
string line = sr.ReadLine();
while (line != null)
{
addSkiTimesPupilCB.Items.Add(line);
line = sr.ReadLine();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" ex.Message);
}
我真的不知道如何在 c# 中做很多事情,請幫助。
uj5u.com熱心網友回復:
由于您的資料以“~”分隔,因此分隔它們的最簡單方法是使用拆分方法。拆分回傳包含元素的字串陣列(在您的情況下,ID 和名稱)
try
{
StreamReader sr = new StreamReader("nameForSkiTimes.txt");
string line = sr.ReadLine();
string[] data;
string label;
while (line != null)
{
data = line.Split("~"); // split on "~" char
if (data.Length > 1) // check if we have at least two elements
{
label = $"{data[0]} {data[1]}"; // Access your ID and your name with index, format as you wish
addSkiTimesPupilCB.Items.Add(label);
}
line = sr.ReadLine();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" ex.Message);
}
uj5u.com熱心網友回復:
如果你喜歡簡短:
在函式中,您只需將這個特殊字符替換為空。
try
{
StreamReader sr = new StreamReader("nameForSkiTimes.txt");
string line = sr.ReadLine();
while (line != null)
{
addSkiTimesPupilCB.Items.Add(line.Replace("~", ""));
line = sr.ReadLine();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" ex.Message);
}
uj5u.com熱心網友回復:
除非這是為了學習使用檔案和流,否則更好的解決方案是使用 json 檔案并使用 Newtonsoft.Json 或 System.Text.Json 進行反序列化。

示例 json,在本例中名為 People.json,與應用程式位于同一檔案夾中。
[
{
"Identifier": 1,
"Name": "Alfreds Futterkiste"
},
{
"Identifier": 2,
"Name": "Die Wandernde Kuh"
},
{
"Identifier": 3,
"Name": "Chop-suey Chinese"
},
{
"Identifier": 4,
"Name": "Antonio Moreno Taquería"
},
{
"Identifier": 5,
"Name": "Antonio Moreno Taquerí"
}
]
json 類
public class Person
{
public int Identifier { get; set; }
public string Name { get; set; }
public override string ToString() => Name;
}
使用 Newtonsoft.Json 將 json 反序列化為 Person 串列并分配 ComboBox。一個 Button,用于獲取 ComboBox 中當前選定的 Person。
public partial class JsonToComboBoxForm : Form
{
public JsonToComboBoxForm()
{
InitializeComponent();
Shown = OnShown;
}
private void OnShown(object sender, EventArgs e)
{
var fileName =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"People.json");
var json = File.ReadAllText(fileName);
PeopleComboBox.DataSource =
JsonConvert.DeserializeObject<List<Person>>(json);
}
private void CurrentButton_Click(object sender, EventArgs e)
{
Person current = (Person)PeopleComboBox.SelectedItem;
MessageBox.Show($@"{current.Identifier, -5}{current.Name}");
}
}
或者同時顯示識別符號和名稱

public class Person
{
public int Identifier { get; set; }
public string Name { get; set; }
public override string ToString() => $"{Identifier} - {Name}";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/452660.html
下一篇:如何從禁用按鈕中洗掉黑色邊框?
