如何从文本文件中读取随机行并将标签中的文本更改为该随机行,然后在我编码的拖放(下方)后,标签将更改文本。语言是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();
答案 0 :(得分:2)
这不是世界上最有效的实现,但如果文件不是太大,您可以执行以下操作从文件中获取随机行,如本回答here中所述:< / p>
string[] lines = File.ReadAllLines(file_location);
Random rand = new Random();
return lines[rand.Next(lines.Length)];