JhWOLFJh
JhWOLFJh

Reputation: 67

How to randomize the text in a label

How to read a random line from a text file and change the text in the label to be that random line, then after a drag and drop which i have coded(below) the label will change the text. The language is c#. I am a beginner so i apologize if this is a stupid question.

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
    }

Also this is how ive been changing the labels text however this isn't it isn't randomized

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

Upvotes: 0

Views: 901

Answers (1)

Baldrick
Baldrick

Reputation: 11860

Not the most efficient implementation in the world, but you could do the following to get a random line from a file, if the file isn't too big, as described in this answer here:

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

Upvotes: 2

Related Questions