在C#窗体中自动完成两个文本框



我需要朝着正确的方向推动。我有一个表单,它有两个文本框-一个启用了自动完成功能,并从DataReader获取数据(txtBx1(,另一个(txtBsx2(我正试图使用txtBx1的值来完成。

因此,当我开始输入txtBx1时,自动完成功能如预期一样工作,但我希望txtBx2同时填充用于检索数据的查询第二列中的数据。

例如,在txtBx1中,我正在键入一个模块参考号,因此我希望在txtBx1中的自动完成"正在进行"或"完成"时,将模块名称填充到txtBx2中。到目前为止,我所拥有的是;

private void Form2_Load(object sender, EventArgs e)
{
OracleConnection oraCon = new OracleConnection("Data Source=(DESCRIPTION="
+ "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxxx)(PORT=1521)))"
+ "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME = TBL)));"
+ "User Id=username;Password=password;");
oraCon.Open();

OracleCommand ocmodref = new OracleCommand(" SELECT module.reference as ModuleRef, module.name as ModuleName FROM TBL_Module module ", oraCon);
//OracleCommand ocmodname = new OracleCommand(" SELECT module.name as ModuleName FROM TBL_Module module where module.reference = '" + txtBx1.Text + "' ", oraCon);

OracleDataReader DRModRef = ocmodref.ExecuteReader();
//OracleDataReader DRModName = ocmodname.ExecuteReader();
AutoCompleteStringCollection automodreftext = new AutoCompleteStringCollection();
//AutoCompleteStringCollection automodnametext = new AutoCompleteStringCollection();
while (DRModRef.Read() )
{

automodreftext.Add(DRModRef.GetString(0));
automodreftext.Add(DRModRef.GetString(1));
//automodnametext.Add(DRModName.GetString(0));
}

txtBx1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtBx1.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtBx1.AutoCompleteCustomSource = automodreftext;
txtBx2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtBx2.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtBx2.AutoCompleteCustomSource = automodreftext;
oraCon.Close();
}

我已经评论了我之前尝试过的部分,但没有成功,但我把它们留在了那里,以防你发现我错过了什么。此外,我还尝试触发txtBx1的TextChanged事件,这样当用户搜索模块引用时文本发生变化时,这会自动完成txtBx2的名称,但遗憾的是,没有乐趣!

如果你能引导我走上正确的道路,我将不胜感激。

谨致问候,

要显示与所选Ref#匹配的名称,反之亦然,请按如下方式使用TextChanged事件:

private void txtBx1_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
StringCollection customSource = tb.AutoCompleteCustomSource;
int index = customSource.IndexOf(tb.Text);
if (index >= 0)
{
txtBx2.Text = txtBx2.AutoCompleteCustomSource[index];
}
else
{
txtBx2.Text = tb.Text;
}
}
private void txtBx2_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
StringCollection customSource = tb.AutoCompleteCustomSource;
int index = customSource.IndexOf(tb.Text);
if (index >= 0)
{
txtBx1.Text = txtBx1.AutoCompleteCustomSource[index];
}
else
{
txtBx1.Text = tb.Text;
}
}

只需确保您设置了txtBx2.AutoCompleteCustomSource = automodnametext,并将您想要的自动完成转换应用于原始字符串。

预期的行为将在两个文本框之间复制文本,只要只输入一个;在选择/键入匹配字符串时,另一个文本框也将显示所需的目标字符串(如果应用了转换(。

最新更新