Click here to Skip to main content
15,847,077 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
I create one table and data grid control and two Colum that is id and name and two textbox id and name .I want that when I click on my grid the selected value will display on their cross ponding textbox such as id and name.   I create I button for show that show the value that is store in database and one button is update I want when I click on update button the selected row in data grid is display in tbxid and tbxname text box in my form . 

I done following code on show button 
 private void button Click(object sender, RoutedEventArgs e) {
        var data = from p in db.gridtbls select p;
        myDataGrid.ItemsSource = data.ToList();

    }

and I used following coding on update button var id = myDataGrid.SelectedValue; tbxname.Text = id.ToString(); tbxid.Text = id.ToString();

but we get the value in textbox name is such as {ID=1 Name="aqib '} is shown in txbname text box . I want that only print in name textbox is "aqib" and id is "1".

how we solve it.

​
Posted

1 solution

The simplest way is to use the built in data binding to get user selections.
C#
// Example data binding class
public class MyData
{
  public int Id { get; set; }
  public string Name { get; set; }
}


XAML for displaying the data
XML
<listview x:name="lst_Data" xmlns:x="#unknown">
 <listview.view>
  <gridview>
   <gridview.columns>
    <gridviewcolumn header="ID" displaymemberbinding="{Binding Id}" />
    <gridviewcolumn header="Name" displaymemberbinding="{Binding Name}" />
   </gridview.columns>
  </gridview>
 </listview.view>
</listview>


And something along these lines when loading and binding the data here
C#
public void LoadMyData()
{
 MyData[] _myData = FetchMyData(); // All you really need is an IEnumerable to bind data to
 lst_Data.DataContext = typeof(MyData);
 lst_Data.ItemsSource = _myData;
}

And then to get which data is selected by the end user
C#
public void UserSelectedSomething(object sender, EventArgs e)
{
 if (lst_Data.SelectedItem == null)
   return;
 
 MyData selectedData = lst_Data.SelectedItem as MyData;

 if (selectedData == null)
   // Oops!  Handle
 else
   // Do something with data
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900