我在SQL Server数据库中有一个名为" course"的表,其中包含60个课程。
该表包含两列:COURSE_ID (PK), COURSE_NAME
我使用存储过程从数据库中获取所有课程:
create PROC [dbo].[GET_ALL_COURSES]
AS
SELECT * FROM COURSE
并像这样填充ComboBox
:
public FORM_CRS()
{
InitializeComponent();
CMB_COURSE.DataSource = CRS.GET_ALL_COURSES();
CMB_COURSE.DisplayMember = "COURSE_NAME";
CMB_COURSE.ValueMember = "COURSE_ID";
}
当我点击ComboBox
中的某个课程时,我想在COURSE_ID
中显示该课程的TextBox
,但我不知道如何。
答案 0 :(得分:1)
使用comboBox创建一个事件,例如onSelectedIndexChanged ..
void cmbCourse_onSelectedIndexChanged(object sender,EventArgs e) {
yourTextBoxName.Text=CMB_COURSE.SelectedItem.ToString();}
答案 1 :(得分:1)
在填充SelectedValueChanged
后立即订阅ComboBox
个活动:
CMB_COURSE.DataSource = CRS.GET_ALL_COURSES();
CMB_COURSE.DisplayMember = "COURSE_NAME";
CMB_COURSE.ValueMember = "COURSE_ID";
CMB_COURSE.SelectedValueChanged += (s, e)
=> textBox1.Text = CMB_COURSE.SelectedValue.ToString();
当您的ComboBox
选项发生变化时,您的TextBox
会显示当前的COURSE_ID
值。
答案 2 :(得分:0)
CMB.Click(object sender, EventArgs e) //click, changedvalue or something else what you want - change it for your neccesity
{
txt.Text = ((ComboBoxItem)CMB_COURSE.SelectedItem).Content.ToString();
//or, i can't test it now, well do it and edit this answer
txt.Text = CMB_COURSE.SelectedValue.ToString();
//or:
DataRowView row = (DataRowView)CMB_COURSE.SelectedItem;
if (row != null)
{
txt.Text = row[0] + " " + row[1];
}
}
这里的最后一个解决方案: https://stackoverflow.com/a/8518930/3810460
答案 3 :(得分:0)
首先,我认为您应该将此link作为参考。
接下来,请认为这段代码符合您的要求:
private List<Course> Courses = new List<Course>();
public Form1()
{
InitializeComponent();
Courses.Add(new Course("Computer Science",1));
Courses.Add(new Course("English", 2));
Courses.Add(new Course("Art", 3));
Courses.Add(new Course("Biology", 4));
Courses.Add(new Course("Philosophy", 5));
Courses.Add(new Course("Humanities", 6));
CourseCB.DataSource = Courses;
CourseCB.SelectedText = Courses.ElementAt(0).CourseName;
CourseCB.DisplayMember = "CourseName";
CourseCB.ValueMember = "CourseID";
}
private void OnValueChanged(object sender, EventArgs e)
{
if (CourseCB.SelectedIndex != -1)
{
CourseIDTB.Text = CourseCB.SelectedValue.ToString();
}
}
public class Course
{
private string myCourseName;
private int myCourseID;
public string CourseName
{
get { return this.myCourseName; }
set { this.myCourseName = value; }
}
public int CourseID
{
get { return this.myCourseID; }
set { this.myCourseID = value; }
}
public Course(string name, int ID)
{
this.CourseName = name;
this.CourseID = ID;
}
}
您具有正确的格式,但要正确使用它,您需要将对象的属性值提供给DisplayMember和ValueMember值,而不是从SQL引用提供。
我建议您执行查询,然后将值插入到Course对象中,您可以使用此代码。