【问题标题】:Can I make a dynamic combo Box from a text file?我可以从文本文件中制作动态组合框吗?
【发布时间】:2021-04-12 19:40:21
【问题描述】:

我想做一个这样的组合框:

但是这些框不应该是硬编码的,它们应该来自这样的文本文件:

在文本文件中添加数据应导致添加组合框。每个组合框也应该有相同的选项列表,它们是 1,2,3,4

我做了以下类来读写文本文件,但是我在互联网上找不到任何资源来将这些文本文件转换为组合框。

public static string ReadFromTextFile(string path)
        {
            if (File.Exists(path))
            {
                string data;
                using (StreamReader r = new StreamReader(path))
                {
                    data = r.ReadToEnd();

                }
                if (data != "")
                {
                    data = "[" + data + "]";
                }
                return data;
            }
            return null;

   }
public static void WriteToTextFile(string path, string data, bool append = true, int count = 1)
        {
            if (!File.Exists(path))
            {
                var file = File.Create(path);
                file.Close();
            }
            using (StreamWriter writer = new StreamWriter(path, append: append))
            {
                if (!append)
                {
                    //remove opening bracket "[" from data passed
                    data = data.Trim().Substring(1, data.Trim().Length - 1);
                    //remove last bracket "]" from data passed
                    data = data.Trim().Substring(0, data.Trim().Length - 1);
                }
                if (count != 0)
                {
                    data = data + ",";
                }
                writer.WriteLine(data);
            }
        }
 public static DataTable ConvertToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties =
                TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            if (data != null)
            {
                foreach (T item in data)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyDescriptor prop in properties)
                        row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                    table.Rows.Add(row);
                }
            }
            return table;
        }

【问题讨论】:

  • 快速浏览一下您的代码与您的问题不符。您的文本文件显示 Food,&lt;new-line&gt;Water,,而您的代码正在解析方括号并使用 DataTables 执行某些操作。你需要重写你的问题
  • 是的,如果文本文件包含所有必需的信息(名称、选择选项等),则可以

标签: c# .net visual-studio winforms combobox


【解决方案1】:

我现在没有可用的视觉工作室。所以,我会给你前进的方向。

  1. 读取该行并将其拆分为字符串数组。

    字符串[] arr= line.Split(",");

  2. 第一个(比如食物)是标题,其余的是值。

  3. 遍历数组。

    for (int i=1;i

  4. 将其添加到组合框项目中,例如cbo.Items.Add(arr[i])

遍历文件中的行,您将获得所需的输出。

【讨论】:

    【解决方案2】:

    您可以使用字符串“Food”/“Water”作为 ComboBox 的 Name 属性来识别每个 ComboBox。

    另外,请注意应该为每个 ComboBox 设置不同的位置。

    private void buttonCreateComboBox_Click(object sender, EventArgs e)
    {
        int locationX = 50;
        int locationY = 10;
    
        string line;
        System.IO.StreamReader file =
            new System.IO.StreamReader(@"C:\Users\Administrator\Desktop\test.txt");
        while ((line = file.ReadLine()) != null)
        {
            // Remove the extra ','
            string comboName = line.Substring(0, line.Length - 1);
    
            ComboBox comboBox = new ComboBox();
            comboBox.Name = comboName;
            comboBox.Items.AddRange(new object[] { 1, 2, 3, 4 });
            comboBox.Location = new Point(locationX, locationY);
            this.Controls.Add(comboBox);
    
            Label label = new Label();
            label.Text = comboName;
            label.Location = new Point(0, locationY);
            this.Controls.Add(label);
    
            locationY += 30;
        }
    
        file.Close();
    }
    

    如果你想访问特定的ComboBox,可以拨打Control.ControlCollection.Find(String, Boolean) Method获取。

    private void buttonGetComboWaterText_Click(object sender, EventArgs e)
    {
        ComboBox comboWater = (ComboBox)this.Controls.Find("Water", true)[0];
        MessageBox.Show(comboWater.Text);
    }
    

    【讨论】:

      【解决方案3】:

      没有详细说明(不知道为什么需要DataTable等),我将从标题中回答您的主要问题。

      这是我的文本文件的外观,如果您逐行阅读,则无需逗号:

          public void ReadFromTextFile(string path)
          {
              if (File.Exists(path))
              {
                  using (StreamReader r = new StreamReader(path))
                  {
                      String line;
                      while ((line = r.ReadLine()) != null)
                      {
                          CreateComboBox(line.ToString());
                      }
                  }
              }
          }
      
          public void CreateComboBox(string definition)
          {
              var combo = new ComboBox();
              combo.Name = definition;
              combo.Items.AddRange(new object[] { "1", "2", "3", "4" });
              var label = new Label();
              label.Text = definition;
              this.flowLayoutPanel1.Controls.Add(label);
              this.flowLayoutPanel1.Controls.Add(combo);
          }
      
          private void Form1_Load(object sender, EventArgs e)
          {
              ReadFromTextFile(@"c:\temp\MyTest.txt");
          }
      

      【讨论】:

      • 如果您想或需要更进一步,请在文本文件中提供其他数据。然后你必须调整数据读取并替换 "1","2","3","4"
      【解决方案4】:

      使用File.ReadAllLines(...)短读txt。
      Point控制位置。
      delegate 附加到SelectedIndexChanged,我想您下一步将需要它。

      private void Form1_Load(object sender, EventArgs e)
      {
          var lines = File.ReadAllLines(@"src.txt").Select(str => str.Replace(",", "")).ToList();
      
          Label lbl, lastLbl = null;
          ComboBox combo, lastCombo = null;
          for (int i = 0; i < lines.Count(); i++)
          {
              lbl = new Label();
              lbl.Text = lines[i];
              
              if (i > 0) // adjust position
                  lbl.Location = new Point(lastLbl.Location.X, lastLbl.Location.Y + lastLbl.Height);
      
              this.Controls.Add(lbl);
              lastLbl = lbl;
      
              combo = new ComboBox();
              combo.DataSource = new List<int>() { 1, 2, 3, 4 };
              if (i > 0) // adjust position
                  combo.Location = new Point(lastCombo.Location.X, lastCombo.Location.Y + lastCombo.Height);
              else
                  combo.Location = new Point(lbl.Width + 5, 0);
              //combo.SelectedIndexChanged += (s, a) => {  }; // action you may need
              this.Controls.Add(combo);
              lastCombo = combo;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-18
        • 2017-06-04
        • 2021-12-29
        • 1970-01-01
        • 2018-09-10
        • 2019-08-23
        • 2014-02-14
        • 2023-01-28
        相关资源
        最近更新 更多