C#如何在C中刷新串行端口#
我想让我的应用程序可以刷新c#中的串行端口。当端口列表(在组合框中)为空时,我点击按钮“刷新”,它工作正常并显示活动端口列表。但是如果我断开了C#如何在C中刷新串行端口#,c#,visual-studio,combobox,serial-port,C#,Visual Studio,Combobox,Serial Port,我想让我的应用程序可以刷新c#中的串行端口。当端口列表(在组合框中)为空时,我点击按钮“刷新”,它工作正常并显示活动端口列表。但是如果我断开了串行端口的连接,并点击了刷新按钮,实际上必须使端口列表(在组合框中)为空,因为串行端口已断开连接。那么,当我点击“刷新”按钮并且条件断开时,如何使所有端口列表(在组合框中)为空 这是我在刷新按钮中的代码: private void button2_Click_2(object sender, EventArgs e) { if(String.IsN
串行端口
的连接,并点击了刷新
按钮,实际上必须使端口列表(在组合框中)为空,因为串行端口已断开连接。那么,当我点击“刷新”按钮并且条件断开时,如何使所有端口列表(在组合框中)为空
这是我在刷新按钮中的代码:
private void button2_Click_2(object sender, EventArgs e)
{
if(String.IsNullOrEmpty(cboPort.Text))
{
comm.SetPortNameValues(cboPort);
for (int i = 0; i < cboPort.Items.Count; i++)
{
string value = cboPort.GetItemText(cboPort.Items[i]);
if (String.IsNullOrEmpty(value))
{
string a = cboPort.SelectedIndex.ToString();
return;
}
else
{
cboPort.SelectedIndex = 0;
}
}
}
else if ((cboPort.Text) != " " && cboPort.SelectedIndex == -1)
{
cboPort.Text = " ";
return;
}
}
我的任务是:
1。我连接串行端口
2.我运行我的应用程序
3.我断开串行端口
4.我点击刷新
5.最终结果是组合框中的端口列表为空
谢谢你的帮助和回复,我在c#还是新手。你好 我终于得到了答案 这是对setportnamevalues的修改:
public void SetPortNameValues(object obj)
{
foreach (string str in SerialPort.GetPortNames())
{
((ComboBox)obj).Items.Add(str);
}
}
public void SetPortNameValues(object obj)
{
string[] ports = SerialPort.GetPortNames(); // load all name of com ports to string
((ComboBox)obj).Items.Clear(); //delete previous names in combobox items
foreach (string port in ports) //add this names to comboboxPort items
{
((ComboBox)obj).Items.Add(port); //if there are some com ports ,select first
}
if (((ComboBox)obj).Items.Count > 0)
{
((ComboBox)obj).SelectedIndex = 0;
}
else
{
((ComboBox)obj).Text = " "; //if there are no com ports ,write Empty
}
}
在此按钮操作中的修改:
private void button2_Click_2(object sender, EventArgs e)
{
comm.SetPortNameValues(cboPort);
}
是的,我终于得到了我想要的 我的解决方案如下
private void InitializePortSetting()
{
mDateTime = DateTime.Now;
//1. Setting port list
// Get a list of serial port names.
portList = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in portList)
{
port_name.Items.Add(port);
}
}
private void serialPort_OnClick(object sender, EventArgs e)
{
port_name.Items.Clear();
port_name.Text = "";
//port_name.Dispose();
// Get a list of serial port names.
portList = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in portList)
{
port_name.Items.Add(port);
}
}