0

我曾经做过DataGridViewComboBoxColumnComboBoxDataGridViewComboBox的还不够好。我需要我ComboBox没有重复的价值观。这是一个例子:

苹果
黑莓
Chrome
苹果

我想删除多次出现的值。我怎样才能做到这一点?

这是我的代码:

OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
Dataset data = new Dataset();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string path = "Data Source = "+".\\"+"test.accdb";
string conStr = "Provider = Microsoft.ACE.OleDb.12.0;"+@path;
conn.Open();
string sql = "SELECT * FROM Table1;"
cmd = new OleDbCommand(sql,conn);
adapter = new OleDbDataAdapter(cmd);
data = new Dataset();
adapter.Fill(data,"Table1");
DataGridViewComboBoxColumn testcolumn = new DataGridViewComboBoxColumn();
testcolumn.Name = "test na ja";
testcolumn.Datasource = data.table[0];
testcolumn.ValueMember = "Remedy";
testcolumn.DisplayMember = "Remedy";
dataGridview1.Columns.Add(testcolumn);
conn.Close()
4

2 回答 2

0

更改SELECT语句以返回不同的值remedy

string sql = "SELECT DISTINCT remedy FROM Table1;"

如果你想订购它:

string sql = "SELECT DISTINCT remedy FROM Table1 ORDER BY remedy ASC;"

或者

string sql = "SELECT DISTINCT remedy FROM Table1 ORDER BY remedy DESC;"
于 2011-04-07T09:19:56.387 回答
0

除了将 distinct 语句应用于您的 SQL 之外,还可以DataTable在创建第二个表时对原始语句应用 distinct ,如下所示(包含单元测试和帮助类,我曾经对此进行原型制作)。

我在下面添加了一条注释以突出显示应用不同的行 - 您使用的是 .ToTable() 方法,该方法采用布尔参数 Distinct 指定仅返回不同的行。

[TestMethod]
public void CreateDistinctDataTable()
{
    DataTable originalTable = CreateDataTable();

    AddDataToTable("Fred", "Bloggs", originalTable);
    AddDataToTable("Fred", "Bloggs", originalTable);
    AddDataToTable("John", "Doe", originalTable);

    // This is the key line of code where we use the .ToTable() method
    DataTable distinctTable = originalTable.DefaultView.ToTable( /*distinct*/ true);

    // The original table has two rows with firstname of Fred
    Assert.AreEqual(2, originalTable.Select("firstname = 'Fred'").Length);

    // The new table only has one row with firstname of Fred
    Assert.AreEqual(1, distinctTable.Select("firstname = 'Fred'").Length);
}

private DataTable CreateDataTable()
{
    DataTable myDataTable = new DataTable();

    DataColumn myDataColumn;

    myDataColumn = new DataColumn();
    myDataColumn.DataType = Type.GetType("System.String");
    myDataColumn.ColumnName = "firstname";
    myDataTable.Columns.Add(myDataColumn);

    myDataColumn = new DataColumn();
    myDataColumn.DataType = Type.GetType("System.String");
    myDataColumn.ColumnName = "lastname";
    myDataTable.Columns.Add(myDataColumn);

    return myDataTable;
}

private void AddDataToTable(string firstname,  string lastname, DataTable myTable)
{
    DataRow row = myTable.NewRow();

    row["firstname"] = firstname;            
    row["lastname"] = lastname;

    myTable.Rows.Add(row);
} 

另一个想法是我建议不要在 SQL 语句中从表中选择 *。如果添加更多列(特别是像 blob 之类的东西),这可能会对性能产生影响,也可能意味着您获得的列会破坏查询的独特性质。

于 2011-04-07T09:37:54.567 回答