我已经将DataGridView绑定正确地绑定到我的数据表但是我正在尝试使自动完成功能正常运行其中一个文本框列。自动完成工作正在运行,但我试图将其限制为datagridview上的只有一列。目前它要么为每一列做,要么根本没有。有任何想法吗?代码如下。
private void dataGridDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridDetail.CurrentCell.ColumnIndex == 2)
{
var source = new AutoCompleteStringCollection();
String[] stringArray = Array.ConvertAll<DataRow, String>(products.Select(), delegate(DataRow row) { return (String)row["code"]; });
source.AddRange(stringArray);
TextBox prodCode = e.Control as TextBox;
if (prodCode != null)
{
prodCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
prodCode.AutoCompleteCustomSource = source;
prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
}
答案 0 :(得分:5)
尝试释放prodCode.AutoCompleteCustomSource
,如果它不是正确的列:
private void dataGridDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridDetail.CurrentCell.ColumnIndex == 2)
{
var source = new AutoCompleteStringCollection();
String[] stringArray = Array.ConvertAll<DataRow, String>(products.Select(), delegate(DataRow row) { return (String)row["code"]; });
source.AddRange(stringArray);
TextBox prodCode = e.Control as TextBox;
if (prodCode != null)
{
prodCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
prodCode.AutoCompleteCustomSource = source;
prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}else
prodCode.AutoCompleteCustomSource = null;
}
答案 1 :(得分:2)
您的if条件只是检查用户当前是否选择了第三列。
您想让所有列都可编辑吗?或者只是当前选定行中的一个单元格?如何通过表单中的另一个按钮触发编辑?在这种情况下,当编辑变为活动时,可以选择任何单元格吗?
您需要索引到正确的列并将其设置为自动完成。
答案 2 :(得分:1)
Abuleen 的建议是最好的!我对它做了一点改进,因为else语句中的行将抛出类型的错误 当前上下文中不存在变量
因此从他的代码:
private void dataGridDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if(dataGridDetail.EditingControl.GetType()==typeof(DataGridViewTextBoxEditingControl))
{
TextBox prodCode = e.Control as TextBox;
if (dataGridDetail.CurrentCell.ColumnIndex == 2)
{
var source = new AutoCompleteStringCollection();
String[] stringArray = Array.ConvertAll<DataRow, String>(products.Select(), delegate(DataRow row) { return (String)row["code"]; });
source.AddRange(stringArray);
TextBox prodCode = e.Control as TextBox;
if (prodCode != null)
{
prodCode.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
prodCode.AutoCompleteCustomSource = source;
prodCode.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
}
else { prodCode.AutoCompleteCustomSource = null; }
}
}