读书人

C# 查询数据库某个表绑定到下拉框时怎

发布时间: 2013-11-14 22:02:51 作者: rapoo

C# 查询数据库某个表绑定到下拉框时如何默认初始值
如题,下面是案例:


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.SqlClient;

namespace F6
{
public partial class UpdateUsers : Form
{
private System.Data.DataTable DT = new System.Data.DataTable();
private SqlDataAdapter SDA = new SqlDataAdapter();
private SqlConnection conn = new SqlConnection();


public UpdateUsers()
{
InitializeComponent();
}

public DataTable selectDutys()
{
DT.Clear();
conn = new SqlConnection(SQLForF6.conStr);
conn.Open();
SqlCommand scSelectDutys = new SqlCommand("select dutyid,dutyname from dutys order by dutyid asc", conn);
SDA = new SqlDataAdapter(scSelectDutys);
SDA.Fill(DT);
conn.Close();
scSelectDutys.Dispose();
return DT;
}

private void UpdateUsers_Load(object sender, EventArgs e)
{

//在窗体load事件为下拉框绑定数据
selectDutyCombox.DataSource = null;
selectDutyCombox.DataSource = selectDutys();
selectDutyCombox.DisplayMember = "dutyname";
selectDutyCombox.ValueMember = "dutyid";
}
}
}


通过上面的代码,在启动这个窗口时,能把从数据库查询出来的数据绑定在下拉框,可每次默认的初始值都是

select dutyid,dutyname from dutys order by dutyid asc

中查询出来的第一行的值。
我能否同时实现下面两个功能:
1/将查询出来的数据绑定在下拉框,
2/可以从查询出来的数据中任选一条数据作为窗体启动时下拉框的初始值
[解决办法]
通过SelectedIndex设置,可以通过comboBox1.Items.IndexOf得到索引

读书人网 >C#

热点推荐