-1

I have a listbox that is loaded from a SQL table. Here is the code:

 private void DisplaySubjects()
    {
        SqlConnection conn = new SqlConnection(zSQL_Variables.csNotebook);
        conn.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(
        "SELECT DISTINCT Subject,ID from Subjects", conn);
        adapter.Fill(ds);
        this.lbxSubjects.DataSource = ds.Tables[0];
        this.lbxSubjects.DisplayMember = "Subject";
        this.lbxSubjects.ValueMember = "Subject"; 
        lblSubjectsCount.Text = "[" + lbxSubjects.Items.Count.ToString() + "]";
    }

The table loads correctly. I have set up a drag and drop operation which takes an item from the listbox and drops it in a textbox. Instead of getting the selected field from the listbox I get "System.Data.DataRowView" instead. Here is my code for the Drag and Drop operations.

 private void txtFindSubject_DragDrop(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.All;
    }

    private void txtFindSubject_DragEnter(object sender, DragEventArgs e)
    {
        txtFindSubject.Text = (string)e.Data.GetData(DataFormats.Text);
    }

    private void lbxSubjects_MouseDown(object sender, MouseEventArgs e)
    {
        lbxSubjects.DoDragDrop(lbxSubjects.SelectedItem.ToString(), DragDropEffects.Copy);
      
    }

What am I doing wrong?

  • Does this answer your question? [Why I get "System.Data.DataRowView" instead of real values in my Listbox?](https://stackoverflow.com/questions/15428542/why-i-get-system-data-datarowview-instead-of-real-values-in-my-listbox) – Maxim Feb 03 '22 at 01:45
  • https://stackoverflow.com/questions/8786637/system-data-datarowview-c-sharp – Maxim Feb 03 '22 at 01:46
  • Thanks for the prompt reply. Unfortuntely it doesn't. – user2961581 Feb 03 '22 at 01:51
  • 1
    What type you get in lbxSubjects.SelectedItem ? And why you don't use SelectedValue? – Maxim Feb 03 '22 at 02:27

1 Answers1

0

In my tests, it looks like you have the code in the (destination) text box events backwards in addition to Maxim’s comment. Try the changes below, they appear to work in my tests.

private void txtFindSubject_DragDrop(object sender, DragEventArgs e) {
  txtFindSubject.Text = e.Data.GetData(DataFormats.StringFormat).ToString();
}
private void txtFindSubject_DragEnter(object sender, DragEventArgs e) {
  e.Effect = DragDropEffects.All;
}

private void lbxSubjects_MouseDown(object sender, MouseEventArgs e) {
  lbxSubjects.DoDragDrop(lbxSubjects.SelectedValue, DragDropEffects.Copy);
}
JohnG
  • 9,259
  • 2
  • 20
  • 29