在单独的表单上显示文本框中的选定列表框项目?

时间:2015-04-28 20:03:21

标签: c# listbox dataset

我正在尝试在列表框中选择一个选定的项目,并以不同的形式显示在文本框中。我希望当我单击MainForm上的按钮时它会触发,以便所选项目显示在textBox中

在我的主要形式中,我有:

public static string myListBoxString;

private void lstDictionary_SelectedIndexChanged(object sender, EventArgs  e)
{
     myListBoxString = lstDictionary.SelectedItem.ToString();
}

private void btnEdit_Click(object sender, EventArgs e)
{
   EditWordForm myEditWordForm = new EditWordForm();
   myEditWordForm.SelectedValue = myListBoxString;
   myEditWordForm.ShowDialog();

   this.dictionaryTableAdapter.Fill(this.dictionaryDataSet.Dictionary);

}

在我尝试放置所选单词的第二种形式中:

public partial class EditWordForm : Form
{
    public EditWordForm()
    {
        InitializeComponent();

        wordTextBox.Text = MainForm.myListBoxString;            
    }

    public string SelectedValue
    {
        set
        {
           wordTextBox.Text = value;
        }
    }


}

编辑*

private void button1_Click(object sender, EventArgs e)
{
 using (SqlConnection connection =  new SqlConnection(ConnectionString)
 {
     connection.Open();
     SqlCommand cmd = new SqlCommand("update dictionary set word=@word", connection);

            cmd.Parameters.AddWithValue("@word", wordTextBox.Text);
            cmd.ExecuteNonQuery();
            this.Close();
        }
    }

现在我能够编辑我想将其保存到数据库中的单词。目前,当它保存时,它将替换所有10个单词与新单词而不是一个特定条目。 从我所阅读和查找的内容看起来这个代码应该可以工作,但到目前为止它只是在运行应用程序后在文本框中显示一个空字段。我唯一能想到的是我使用数据集来填充初始列表框并将其抛弃?任何指导表示赞赏!

1 个答案:

答案 0 :(得分:0)

在EditWordForm中添加名为SelectedValue的属性

public string SelectedValue
{
     set
     {
          wordTextBox.Text = value;
     }
}

在显示表单之前,从主窗体设置此属性。

private void btnEdit_Click(object sender, EventArgs e)
{
   EditWordForm myEditWordForm = new EditWordForm();
   myEditForm.SelectedValue = lstDictionary.GetItemText(lstDictionary.SelectedItem);

   myEditWordForm.ShowDialog();

   this.dictionaryTableAdapter.Fill(this.dictionaryDataSet.Dictionary);

}