C# 用户在listview中选择项,它将文本文件中的数据显示到标签中
我正在尝试编写一个程序,其中包含一个C# 用户在listview中选择项,它将文本文件中的数据显示到标签中,c#,winforms,listview,dictionary,C#,Winforms,Listview,Dictionary,我正在尝试编写一个程序,其中包含一个列表视图,其中填充了文本文件中的4列数据(4列中的名称、州、城市、邮编),当用户在列表视图中单击一个名称时,它会将名称和电话号码(在文本文件中)显示为两个标签。 以下是我目前的代码: namespace VendorsDictionary { public partial class VendorsDictionary : Form { public VendorsDictionary() {
列表视图
,其中填充了文本文件中的4列数据(4列中的名称、州、城市、邮编),当用户在列表视图
中单击一个名称时,它会将名称和电话号码(在文本文件中)显示为两个标签。
以下是我目前的代码:
namespace VendorsDictionary
{
public partial class VendorsDictionary : Form
{
public VendorsDictionary()
{
InitializeComponent();
}
private Dictionary<string,string> vendorPhones = new Dictionary<string,string>();
private void VendorsDictionary_Load(object sender, EventArgs e)
{
string currentLine;
string[] fields = new string[2];
StreamReader vendorReader = new StreamReader("Vendor.txt");
while (vendorReader.EndOfStream == false)
{
currentLine = vendorReader.ReadLine();
fields = currentLine.Split(',');
vendorPhones.Add(fields[1], fields[6]);
string[] name = { fields[1] };
string[] city = { fields[3] };
string[] state = { fields[4] };
string[] zipcode = { fields[5] };
for (int i = 0; i < name.Length; i++)
{
lvDisplay.Items.Add(new ListViewItem(new[] { name[i], city[i], state[i], zipcode[i] }));
}
}
vendorReader.Close();
}
private void lvDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvDisplay.SelectedItems.Count>0)
{
ListViewItem item = lvDisplay.SelectedItems[0];
lblName.Text = item.SubItems[0].Text;
// lbPhone = ?
// lblPhone.Text = item.SubItems[].Text; - does not work because phone number is not in the listview
}
else
{
lblName.Text = string.Empty;
lblPhone.Text = string.Empty;
}
}
}
}
名称空间字典
{
公共部分类VendorsDictionary:表单
{
公共供应商词典()
{
初始化组件();
}
专用词典供应商电话=新词典();
私有void VendorsDictionary\u加载(对象发送方,事件参数e)
{
串电流线;
字符串[]字段=新字符串[2];
StreamReader vendorReader=新的StreamReader(“Vendor.txt”);
while(vendorReader.EndOfStream==false)
{
currentLine=vendorReader.ReadLine();
字段=currentLine.Split(',');
添加(字段[1],字段[6]);
字符串[]名称={fields[1]};
字符串[]city={fields[3]};
字符串[]状态={fields[4]};
字符串[]zipcode={fields[5]};
for(int i=0;i0)
{
ListViewItem item=lvDisplay.SelectedItems[0];
lblName.Text=item.SubItems[0]。Text;
//lbPhone=?
//lblPhone.Text=item.SubItems[].Text;-不工作,因为电话号码不在列表视图中
}
其他的
{
lblName.Text=string.Empty;
lblPhone.Text=string.Empty;
}
}
}
}
到目前为止,我已经一切正常,除了我无法找出如何从文本文件中获取电话号码以显示在第二个标签中。获取要显示的名称非常简单,因为它位于
列表视图中,但是如何获取要显示的电话号码(文本文件中的最后一列) 您正在将供应商的电话号码存储在字典vendorPhones
中
我仍然不确定文件中存储的数据的格式和结构,以及为什么要循环使用name.length
如果我假设供应商名称是唯一的,您可以从字典中获取所选供应商的电话号码,如下所示
private void lvDisplay_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvDisplay.SelectedItems.Count>0)
{
ListViewItem item = lvDisplay.SelectedItems[0];
lblName.Text = item.SubItems[0].Text;
lblPhone.Text = vendorPhones[item.SubItems[0].Text]; // Get the phone number from dictionary by using the vendor name.
}
else
{
lblName.Text = string.Empty;
lblPhone.Text = string.Empty;
}
}