我正在尝试根据列表框选择将文本框绑定到数据表行。
public Edit(MovieSetSource movieSource)
{
InitializeComponent();
bindingSource = new BindingSource();
bindingSource.DataSource = movieSource.GetMovies().Tables["Movie"];
movieListBox.DataSource = bindingSource;
movieListBox.ValueMember = "Name";
nameText.DataBindings.Add(new Binding("Text", movieListBox, "SelectedItem.Name", true, DataSourceUpdateMode.OnPropertyChanged));
producerText.DataBindings.Add(new Binding("Text", movieListBox, "SelectedItem.Producer", true, DataSourceUpdateMode.OnPropertyChanged));
releaseYearText.DataBindings.Add(new Binding("Text", movieListBox, "SelectedItem.Release Year", true, DataSourceUpdateMode.OnPropertyChanged));
}
这是我绑定电影的方式。
MovieSetSource类在这里:
public class MovieSetSource : ISource
{
private DataSet _movieSet;
private SqlDataAdapter _movieAdapter;
private RottenTomatoesRestClient RTclient;
public MovieSetSource()
{
var movieConnection = new SqlConnection(Properties.Settings.Default.moviesConnectionString);
_movieSet = new DataSet();
_movieAdapter = new SqlDataAdapter("Select * From Movie", movieConnection);
RTclient = new RottenTomatoesRestClient("jcy6eyga8txee776kbn3mfe7");
SqlCommandBuilder movieSQLBuilder = new SqlCommandBuilder(_movieAdapter);
_movieAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
_movieAdapter.Fill(_movieSet, "Movie");
}
public DataSet GetMovies()
{
return _movieSet;
}
}
TextBox的Text属性应使用列表框中的selectedItem进行更新。它还应该在textBox中进行编辑后保存。
答案 0 :(得分:3)
您的代码需要进行一些调整。至于我不确定您的数据源中的确切名称,这里有一个小示例代码(带有虚构值),显示您应该如何面对这种情况:
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Country");
dt.Rows.Add("Name1", "Country1");
dt.Rows.Add("Name2", "Country2");
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = dt;
movieListBox.DataSource = bindingSource;
movieListBox.ValueMember = "Name";
textBoxName.DataBindings.Add(new Binding("Text", movieListBox.DataSource, "Name", true, DataSourceUpdateMode.OnPropertyChanged));
textBoxCountry.DataBindings.Add(new Binding("Text", movieListBox.DataSource, "Country", true, DataSourceUpdateMode.OnPropertyChanged));