【问题标题】:How to randomize the text in a label如何随机化标签中的文本
【发布时间】:2015-02-22 19:13:54
【问题描述】:

如何从文本文件中读取随机行并将标签中的文本更改为该随机行,然后在我已编码(如下)的拖放后,标签将更改文本。语言是c#。我是初学者,如果这是一个愚蠢的问题,我深表歉意。

private void txt_carbs_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.Text))
            e.Effect = e.AllowedEffect;
        // check if the held data format is text
        // if it is text allow the effect 
        else
            e.Effect = DragDropEffects.None;
        // if it is not text do nothing
    }

    private void txt_protien_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.Text))
            e.Effect = e.AllowedEffect;
        // check if the held data format is text
        // if it is text allow the effect 
        else
            e.Effect = DragDropEffects.None;
        // if it is not text do nothing
    }

    private void txt_fats_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.Text))
            e.Effect = e.AllowedEffect;
            // check if the held data format is text
            // if it is text allow the effect 
        else
            e.Effect = DragDropEffects.None;
        // if it is not text do nothing
    }

    private void txt_fats_DragDrop(object sender, DragEventArgs e)
    {
        txt_fats.Text += e.Data.GetData(DataFormats.Text).ToString();
        //add the text into the text box
    }

    private void txt_protien_DragDrop(object sender, DragEventArgs e)
    {
        txt_protien.Text += e.Data.GetData(DataFormats.Text).ToString();
        //add the text into the text box
    }

    private void txt_carbs_DragDrop(object sender, DragEventArgs e)
    {
        txt_carbs.Text += e.Data.GetData(DataFormats.Text).ToString();
        //add the text into the text box
    }

    private void lbl_term_MouseDown(object sender, MouseEventArgs e)
    {
        lbl_term.DoDragDrop(lbl_term.Text, DragDropEffects.Copy);
        // get the text from the label
    }

这也是我更改标签文本的方式,但这不是随机的

StreamReader score =
            new StreamReader(file_location);
        label10.Text = score.ReadLine();

【问题讨论】:

    标签: c# random label text-files


    【解决方案1】:

    不是世界上最有效的实现,但如果文件不是太大,您可以执行以下操作以从文件中获取随机行,如此答案here 中所述:

    string[] lines = File.ReadAllLines(file_location);
    Random rand = new Random();
    return lines[rand.Next(lines.Length)];
    

    【讨论】:

    • 作为对 OP 的警告,每次都声明一个新的随机数不会像他们希望的那样随机...Example.. 不过很容易找到解决这个问题的方法; )
    • @Sayse:同意,这并不完美。但是对于上面示例中的 OP 的目的,它应该没问题。最好将Random 对象初始化为静态类,并且每次都重用同一个对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多