C#同一按钮操作不同ListBox选中项并刷新列表
解决方案:双向修改.ini的OTPM值并刷新ListBox
核心思路
- 把刷新两个ListBox的逻辑抽成独立方法,避免重复代码
- 按钮点击时判断选中项所属的ListBox,执行对应的值修改(listBox1项改false,listBox2项改true)
- 修改完成后立即调用刷新方法,同步更新两个ListBox的内容
修改后的完整代码
1. 刷新ListBox的方法
private void RefreshListBoxes(string targetDirectory) { listBox1.Items.Clear(); listBox2.Items.Clear(); // 获取目录下所有.ini文件 string[] iniFiles = Directory.GetFiles(targetDirectory, "*.ini", SearchOption.TopDirectoryOnly); foreach (string filePath in iniFiles) { // 读取OTPM字段值,替换为你实际的节名 string otpmValue = ReadIniValue(filePath, "你的节名", "OTPM"); if (string.Equals(otpmValue, "true", StringComparison.OrdinalIgnoreCase)) { listBox1.Items.Add(filePath); } else if (string.Equals(otpmValue, "false", StringComparison.OrdinalIgnoreCase)) { listBox2.Items.Add(filePath); } } }
2. 按钮点击事件逻辑
private void btnToggleOTPM_Click(object sender, EventArgs e) { string targetFilePath = null; bool newOtpmValue = false; // 判断选中项来自哪个ListBox if (listBox1.SelectedItem != null) { targetFilePath = listBox1.SelectedItem.ToString(); newOtpmValue = false; } else if (listBox2.SelectedItem != null) { targetFilePath = listBox2.SelectedItem.ToString(); newOtpmValue = true; } else { MessageBox.Show("请先选中一个文件!"); return; } // 修改.ini文件的OTPM值 if (WriteIniValue(targetFilePath, "你的节名", "OTPM", newOtpmValue.ToString().ToLower())) { // 刷新列表 string targetDir = Path.GetDirectoryName(targetFilePath); RefreshListBoxes(targetDir); MessageBox.Show("修改成功!"); } else { MessageBox.Show("修改失败,请检查文件权限!"); } }
3. 补充INI读写的API实现(如果没有的话)
// 读取INI字段值 private string ReadIniValue(string filePath, string section, string key) { StringBuilder sb = new StringBuilder(255); GetPrivateProfileString(section, key, "", sb, sb.Capacity, filePath); return sb.ToString(); } // 写入INI字段值 private bool WriteIniValue(string filePath, string section, string key, string value) { return WritePrivateProfileString(section, key, value, filePath); } // 导入Windows API [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
注意事项
- 把代码中的
"你的节名"替换为你.ini文件中OTPM字段所在的实际节名称 - 确保程序拥有目标目录的读写权限,否则会修改失败
- 在Form的
Load事件中调用一次RefreshListBoxes("你的目标目录路径"),加载初始数据
内容的提问来源于stack exchange,提问作者Katonas
相关产品推荐
相关产品推荐

