Skip to main content
 首页 » 编程设计

c# 从 System.Data.DataRowView 转换为字符串

2024年02月24日27虾米哥

我有一个组合框,其数据源是一个数据表。我需要遍历组合框中的项目,但我该怎么做呢?我需要能够将“System.Data.DataRowView”类型的每个对象转换为字符串。非常感谢任何建议!@

请您参考如下方法:

根据您最近的问题,听起来您正在尝试弄清楚如何根据项目中显示的文本在组合框中查找或设置所选项目。我不确定您是如何设置的,但请查看以下代码,看看是否有帮助:

private void button1_Click(object sender, EventArgs e) 
{ 
    DataTable dt = new DataTable(); 
    dt.Columns.Add("ID", typeof(int)); 
    dt.Columns.Add("Name", typeof(string)); 
 
    dt.Rows.Add(1, "A"); 
    dt.Rows.Add(2, "B"); 
    dt.Rows.Add(3, "C"); 
 
    comboBox1.DataSource = dt; 
    comboBox1.DisplayMember = "Name"; 
    comboBox1.ValueMember = "ID"; 
 
    // use SelectedValue to select the item with ID == 2 
    comboBox1.SelectedValue = 2; 
 
    // use FindStringExact() to find the index of text displayed in the item 
    comboBox1.SelectedIndex = comboBox1.FindStringExact("C"); 
} 

并使用上面设置的组合框,您可以像这样获取显示成员的文本:

private void button2_Click(object sender, EventArgs e) 
{ 
    foreach (var item in comboBox1.Items) 
        MessageBox.Show(((DataRowView)item)["Name"].ToString()); 
}