我正在尝试从访问combobox1
获取数据,但它无效。
我的数据库是.accdb
文件。我的表名是“list”。
列名是:
“ID_lista”=自动编号
“Nome”= smalltext
“链接”=超链接
以下是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace teste_pwd
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public static class Globals
{
public static String ConString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Application.StartupPath + "\\PWD_BD.accdb";
public static OleDbConnection ConnectionString = new OleDbConnection(Globals.ConString);
}
private void Form2_Load(object sender, EventArgs e)
{
Globals.ConnectionString.Close();
pCMB();
}
public void pCMB()
{
try
{
Globals.ConnectionString.Open();
int i = 0;
string query = "SELECT * FROM List";
OleDbDataAdapter dataAdapeter = new OleDbDataAdapter(query, Globals.ConnectionString);
DataSet mydata = new DataSet();
dataAdapeter.Fill(mydata, "List");
comboBox1.DisplayMember = "Texto";
comboBox1.ValueMember = "Valor";
DataTable tb = new DataTable();
tb.Columns.Add("Texto", typeof(string));
tb.Columns.Add("Valor", typeof(int));
for (i = 0; i <= mydata.Tables[0].Rows.Count - 1; i++)
{
tb.Rows.Add(mydata.Tables[0].Rows[i].ItemArray[1], mydata.Tables[0].Rows[i].ItemArray[0]);
}
comboBox1.DataSource = tb;
Globals.ConnectionString.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
}
答案 0 :(得分:0)
此代码可能会帮助您将数据添加到组合框中。 此代码适用于vb.net
Dim DrContractor As DataRow
Dim DtContractor As DataTable
Dim i As Integer
strQuery = " SELECT * FROM CONTRACTOR ORDER BY CONTCODE"
Dim DataAdapeter As New SqlDataAdapter(strQuery, myConnection)
Dim dsDivision As New DataSet
'myConnection.Open()
DataAdapeter.Fill(dsDivision, "CONTRACTOR")
DtContractor = dsDivision.Tables("CONTRACTOR")
'myConnection.Close()
cboContractor.Items.Add("ALL")
For i = 0 To DtContractor.Rows.Count - 1
DrContractor = DtContractor.Rows(i)
cboContractor.Items.Add(DrContractor("CONTNAME").ToString & " : " & DrContractor("CONTCODE").ToString)
Next
cboContractor.SelectedIndex = 0
cboContractor.SelectedText = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try