如何从数据库填充组合框并在C#中的索引零上插入新项 [英] How to populate combo box from database and insert new item on index zero in C#
本文介绍了如何从数据库填充组合框并在C#中的索引零上插入新项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码对我有用,但是我无法插入---选择---到第一个索引值为零。
我尝试过:
This code below works for me, but i have not been able to insert ---Select--- to the for first index with value zero.
What I have tried:
private void LoadGrade()
{
using (SQLiteConnection conn = new SQLiteConnection(connstring))
{
try
{
string query = "select GradeCode, GradeName from Grade";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "OrgGrade");
cboGrade.Items.Insert(0,"---Select---);
cboGrade.DisplayMember = "GradeName";
cboGrade.ValueMember = "GradeCode";
cboGrade.DataSource = ds.Tables["OrgGrade"];
}
catch (Exception ex)
{
MessageBox.Show("Error occured loading grade!");
}
}
}
但它对我不起作用。我还希望能够在从数据库中检索时检索并显示组合框上的displaymember和displayvalue,而不会重复项目
but it is not working for me. Also i want to able to retrieve and display the displaymember and displayvalue on the combo box while retrieving from database without items not being repeated
推荐答案
尝试
try
DataTable dt = new DataTable();
dt.Columns.Add("GradeName");
dt.Columns.Add("GradeCode");
dt.Rows.Add("aaa", "11");
var row = dt.NewRow();
row["GradeName"] = "Select";
row["GradeCode"] = "0";
dt.Rows.InsertAt(row, 0);
cboGrade.DisplayMember = "GradeName";
cboGrade.ValueMember = "GradeCode";
cboGrade.DataSource = dt;
您无法直接在ComboBox上工作,因为您已将其绑定到DataSet。相反,您需要使用 DataRowCollection.InsertAt方法(DataRow,Int32)(System.Data) [ ^ ]
所以示例可能是(未经测试) :
You can't work directly on the ComboBox as you have bound it to a DataSet. Instead, you need to work with where the data is located using DataRowCollection.InsertAt Method (DataRow, Int32) (System.Data)[^]
So example could be (untested):
var insertRow = ds.Details.NewDetailsRow();
insertRow.Id = "0";
insertRow.Description = "---Select---";
ds.Details.Rows.InsertAt(insertRow, 0);
private void LoadGrade()
{
using (SQLiteConnection conn = new SQLiteConnection(connstring))
{
try
{
string query = "select GradeCode, GradeName from Grade";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "OrgGrade");
cboGrade.DisplayMember = "GradeName";
cboGrade.ValueMember = "GradeCode";
cboGrade.DataSource = ds.Tables["OrgGrade"];
cboGrade.Items.Insert(0,"---Select---);
}
catch (Exception ex)
{
MessageBox.Show("Error occured loading grade!");
}
}
}
这篇关于如何从数据库填充组合框并在C#中的索引零上插入新项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文