You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForm:如何从文本文件随机选一行输出?Next()方法遇问题

Fixing Random Line Selection and Variable Extraction

Let's break down what's going wrong in your code and how to fix it so you can properly select a random line and access all its variables:

Key Issues in Your Current Code

  • Incorrect line selection: In Button1_Click, you’re looping through every line in Spara and setting the text box to a single character (item[index]) instead of picking one random line.
  • Unused split operation: You split each line in the constructor but don’t store the results—this code doesn’t help you later when you need the variables.
  • Hardcoded random range: rng.Next(0,4) limits you to only the first 4 lines, which isn’t dynamic if your file has more or fewer lines.
  • No error handling: You don’t check if the line splits into enough parts, which could cause an IndexOutOfRangeException.

Corrected Code with Explanations

First, fix the file reading to properly close the file (using a using block, which ensures resources are cleaned up):

public Form1() {
    InitializeComponent();
    // Use 'using' to automatically close the file after reading
    using (StreamReader file = new StreamReader(@"C:\Users\razer\Desktop\test.txt", Encoding.Default, false)) {
        string item;
        while ((item = file.ReadLine()) != null) {
            Spara.Add(item);
        }
    }
    rng = new Random();
    // Remove the unused split loop here—we'll split the selected line when the button is clicked
}

Then, rewrite the Button1_Click method to select a random line, split it into variables, and display them clearly:

private void Button1_Click(object sender, EventArgs e) {
    // First, check if we have any lines to select from
    if (Spara.Count == 0) {
        textBox1.Text = "Inga rader hittades i filen.";
        return;
    }

    // Generate a random index for the list of lines (dynamic range based on actual line count)
    int randomLineIndex = rng.Next(Spara.Count);
    // Get the randomly selected line
    string selectedLine = Spara[randomLineIndex];

    // Split the line into variables using "###" as the delimiter
    string[] lineVariables = selectedLine.Split(new string[] { "###" }, StringSplitOptions.None);

    // Now access and display the variables—adjust this based on your desired output format
    if (lineVariables.Length >= 3) {
        // If the line has all expected parts, format them nicely
        textBox1.Text = $"Författare: {lineVariables[0]}\nBoktyp: {lineVariables[1]}\nÅrstyp: {lineVariables[2]}";
    } else {
        // Handle lines that don't match the expected format
        textBox1.Text = $"Ogiltig radformat: {selectedLine}\nFörväntade delar: 3, hittade: {lineVariables.Length}";
    }
}

How This Works

  1. Dynamic Random Line Selection: rng.Next(Spara.Count) picks a valid index for any number of lines in your file, so it works even if the file grows or shrinks.
  2. On-Demand Splitting: We only split the line we actually select, which is more efficient than splitting all lines upfront.
  3. Error Handling: We check if the split gives us enough parts to avoid crashes, and show a helpful message if a line doesn’t follow the expected format.
  4. Clear Output: The variables are displayed in a readable, structured way so you can see all parts of the selected line at once.

Additional Tips

  • If you want to reuse the split variables elsewhere in your form, you could store them in a class-level variable instead of just in the button click method.
  • Double-check that your text file lines follow the X###Y###Z format—any line that doesn’t will trigger the error message, which helps you debug invalid entries quickly.

内容的提问来源于stack exchange,提问作者realme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:10:14