Alexey Ivanov Alexey Ivanov - 18 days ago 7
C# Question

Bind TextBox to DataAdapter

.cs

DataTable dt;
NpgsqlDataAdapter adapter;
NpgsqlCommand selcmd, upcmd, delcmd, inscmd;
NpgsqlConnection conn;
NpgsqlTransaction tran;

public void ReadAndFill()
{
conn.Open();
tran = conn.BeginTransaction();

selcmd.Connection = conn;
selcmd.Transaction = tran;

dt.Clear();
adapter.Fill(dt);
dgMain.ItemsSource = dt.DefaultView;
tran.Commit();
conn.Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ReadAndFill();
DataContext = dt;
}


.xaml

<DataGrid x:Name="dgMain" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" AutoGenerateColumns="False"/>
<TextBox x:Name="textBox" Height="23" TextWrapping="Wrap" Text="{Binding name}" Width="120"/>


So I can edit only the first row of the DataTable dt through the textBox. And data in textBox does not change when you move on DataGrid dgMain. How to fix it?

Answer

In this case, the TextBox should be tied to the DataGrid. I have not found an example of how the TextBox to bind to DataTable / DataSet / DataAdapter and keep the same logic: data in the TextBox will be changed by moving on DataGrid.

Comments