C# 本地txt文件读取至comboBox下拉列表

在网上找了很多资料,最后通过调试,读取项目名称功能是实现了,具体的优化暂时没时间去弄

值得注意的是,页面在返回即刷新的时候要预处理清空下comboBox的值,否则会引起重复

this.combox.Items.Clear();

代码如下:

view plaincopy to clipboardprint?
/// <summary>  
       /// 从txt文件中得到项目名称,再显示到comboBox上  
        /// </summary>  
        private void ConvertTxtToDataSet()  
        {  
            string ReadLine;  
            string[] array;  
            string Path = @"E:\1.TXT";  
 
            StreamReader reader = new StreamReader(Path,   
                                  System.Text.Encoding.GetEncoding("GB2312"));   
            while (reader.Peek() >= 0)  
            {  
                try 
                {  
                    ReadLine = reader.ReadLine();  
                    if (ReadLine != "")   
                    {  
                        ReadLine = ReadLine.Replace("\"", "");  
                        array = ReadLine.Split(',');  
                        if (array.Length == 0)  
                        {  
                            MessageBox.Show("您选择的导入数据类型有误,请重试!");  
                            return;  
                        }  
                        this.comboxQcProName.Items.Add(array[0]);  
                    }  
                }  
                catch (Exception ex)  
                {  
                    MessageBox.Show(ex.ToString());  
                }  
                  
            }  
        } 
/// <summary>
       /// 从txt文件中得到项目名称,再显示到comboBox上
        /// </summary>
        private void ConvertTxtToDataSet()
        {
            string ReadLine;
            string[] array;
            string Path = @"E:\1.TXT";

            StreamReader reader = new StreamReader(Path,
                                  System.Text.Encoding.GetEncoding("GB2312"));
            while (reader.Peek() >= 0)
            {
                try
                {
                    ReadLine = reader.ReadLine();
                    if (ReadLine != "")
                    {
                        ReadLine = ReadLine.Replace("\"", "");
                        array = ReadLine.Split(',');
                        if (array.Length == 0)
                        {
                            MessageBox.Show("您选择的导入数据类型有误,请重试!");
                            return;
                        }
                        this.comboxQcProName.Items.Add(array[0]);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
               
            }
        }

期中TXT里面文件1.txt格式为:

                                         白细胞,"JEF",205.00,0.0351
                                         绿细胞,"JEF",7516.00,0.0382
                                         黑细胞,"JEF",1681.00,0.0675
                                         蓝细胞,"JEF",213.00,0.0563

结论:该函数自动读取文件txt一次读写一行文本,自动循环的读完所有内容

原文地址:https://www.cnblogs.com/liufei88866/p/1762857.html