text box autocomplete not working properly - c#

I am facing problem while work on text box autocomplete in window form application. my collection show 50 records on search. but i receive only 2 in textbox suggestion. why? see code .I am doing this work in txtInput_TextChanged event.
private void txtInput_TextChanged(object sender, EventArgs e)
{
string str = txtInput.Text.ToString();
dv = new DataView(dt);
dv.RowFilter = "MedicineName like '%" + str + "%'";
for (int i = 0; i < dv.Count; i++)
{
string name = dv[i]["MedicineName"].ToString();
nameCollection.Add(name);
}
txtInput.AutoCompleteMode = AutoCompleteMode.Suggest;
txtInput.AutoCompleteSource = AutoCompleteSource.CustomSource;
txtInput.AutoCompleteCustomSource = nameCollection;
//textboxMedicine.BorderStyle = BorderStyle.Fixed3D;
//textboxMedicine.ScrollBars = ScrollBars.Vertical;
}
I also set autocomplete and autocompletesource in property window. but still my textbox autocomplete suggestions not working correctly. please help

Use this AutoCompleteMode.SuggestAppend for AutoCompleteMode
txtInput.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
EDIT:
Change like to LIKE
dv.RowFilter = "MedicineName LIKE '%"+str+"%'";

Related

RowIndex Returns Error in ContextMenuStrip

I've been looking for a way. To Edit, update and delete my data using a contextmenustrip.
Basically what I want is for my contextmenustrip to be able to interact with Datagridview, the problem is whenever I set the code for click event. it shows an error, I am still new in c# so I am probably not figuring something out. this is my code.
private void DgAddnew_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("You can now Edit this data, Choose Update Button To populate, Thank you!", "Edit Data,", MessageBoxButtons.OK, MessageBoxIcon.Information);
int index = e.RowIndex;// get the Row Index
DataGridViewRow selectedRow = dgAddnew.Rows[index];
txtNAME.Text = selectedRow.Cells[1].Value.ToString();
txtADDRESS.Text = selectedRow.Cells[2].Value.ToString();
txtCELLPHONE.Text = selectedRow.Cells[3].Value.ToString();
txtCODE.Text = selectedRow.Cells[4].Value.ToString();
cmbTYPE.Text = selectedRow.Cells[5].Value.ToString();
cmbCOLOR.Text = selectedRow.Cells[6].Value.ToString();
cmbHEELS.Text = selectedRow.Cells[7].Value.ToString();
cmbPAYMENT.Text = selectedRow.Cells[8].Value.ToString();
cmbPRICE.Text = selectedRow.Cells[9].Value.ToString();
cmbRESERVE.Text = selectedRow.Cells[10].Value.ToString();
cmbBONDFEE.Text = selectedRow.Cells[11].Value.ToString();
dpDATEOUT.Text = selectedRow.Cells[12].Value.ToString();
dpDATERETURN.Text = selectedRow.Cells[13].Value.ToString();
}
this work in datagridview. but when i add it on contextmenu all this item doesn't populate, and i get a row index error.
private void EDITToolStripMenuItem_Click_1(object sender, EventArgs e)
{
MessageBox.Show("You can now Edit this data, Choose Update Button To populate, Thank you!", "Edit Data,", MessageBoxButtons.OK, MessageBoxIcon.Information);
int index = e.RowIndex;// get the Row Index
DataGridViewRow selectedRow = dgAddnew.Rows[index];
txtNAME.Text = selectedRow.Cells[1].Value.ToString();
txtADDRESS.Text = selectedRow.Cells[2].Value.ToString();
txtCELLPHONE.Text = selectedRow.Cells[3].Value.ToString();
txtCODE.Text = selectedRow.Cells[4].Value.ToString();
cmbTYPE.Text = selectedRow.Cells[5].Value.ToString();
cmbCOLOR.Text = selectedRow.Cells[6].Value.ToString();
cmbHEELS.Text = selectedRow.Cells[7].Value.ToString();
cmbPAYMENT.Text = selectedRow.Cells[8].Value.ToString();
cmbPRICE.Text = selectedRow.Cells[9].Value.ToString();
cmbRESERVE.Text = selectedRow.Cells[10].Value.ToString();
cmbBONDFEE.Text = selectedRow.Cells[11].Value.ToString();
dpDATEOUT.Text = selectedRow.Cells[12].Value.ToString();
dpDATERETURN.Text = selectedRow.Cells[13].Value.ToString();
}
the part it has "e.RowIndex" Gives error. Is there A way I can declare a global declaration or store a rowIndex to a container and be able to interact with the contextmenustrip,??
I've been figuring it for days and it still doesn't work.
Its my 12days of learning c# as my first language and it frustrates me that I still suck so bad.
pls help me. Thanks.

Populate combobox inside DataGridView with the values of List

I am trying to add a Combobox inside a DataGridView the method where I am managing this is repeated plenty of times if I refresh another combobox that I have in Windows form, I run this method all over again
this.DataGridView1.ColumnCount = Constants.Vacation_Calendar.Total_Calendar_Days + 2;
this.DataGridView1.Columns[0].Name = "Resource";
this.DataGridView1.Columns[0].Width = 100;
this.DataGridView1.Columns[1].Name = "Month";
this.DataGridView1.Columns[1].Width = 60;
DataGridViewComboBoxColumn cb = new DataGridViewComboBoxColumn();
List<Process> getAllProcesses = this.bl_process.getAll_Process();
List<String> getApplication= new List<string>();
foreach (Process process in getAllProcesses)
{
getApplication.Add(process.Application);
}
if (!DataGridView1.Columns.Cast<DataGridViewColumn>().Any(x => x.Name == "ProcessColumn"))
{
cb.HeaderText = "Process";
cb.Name = "ProcessColumn";
cb.Width = 100;
cb.DataSource = getApplication;
cb.ReadOnly = false;
DataGridView1.Columns.Insert(2, cb);
}
I keep getting an Error that I handled with the following code in the designer:
this.DataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.DataGridView1_DataError);
And in code behind:
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e){}
with all this I can't see my list populating the combobox, what's still missing here?
Thank you so much in advance
PS: I added "getApplication" object to the Quickwatches and it's receiving all the values from my List, so it's all good.
don't i need something like a method SelectedIndexChanged bounded to my combobox inside gridview? to see what i am selecting

How can I filter a DataGridView?

I have created a simple DataGridView through the toolbox and have selected data through the wizard (no code in .cs file) from a database. It is working flawlessly as you can see in the picture below:
Now I want to filter the entries in it by contact person name. I have a textbox and search button so when the user enters a "contact person name" such as "Altaf" and then clicks on search, the GridView should refresh and only entries with ticketid=4 should appear.
The only code in the .cs file (which is auto-generated) is:
private void Form2_Load(object sender, EventArgs e)
{
this.tblTicketDetailTableAdapter.Fill(this.sTDataSet1.tblTicketDetail); //auto-generated
}
I tried this in a ButtonClick event as suggested by someone but it generates the error: "Cannot interpret token '{' at position 27"
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = issuerNameDataGridViewTextBoxColumn + "like '%" + txtbxSearch.Text.Trim().Replace("'", "''") + "%'";
dataGridView1.DataSource = bs.DataSource;
I have no experience in DataGridViews or WinForms coding, so please explain in detail.
Thank you everyone that has answered to my query, I really appreciate your help guys. You guys are the most helpful bunch.
I have solved my problem by doing following modifications to my code :
public void btnSearch_Click(object sender, EventArgs e)
{
BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = dataGridView1.Columns[5].HeaderText.ToString() + " LIKE '%" + txtbxSearch.Text + "%'";
dataGridView1.DataSource = bs;
}
Thank you again.
Try this:
foreach (System.Windows.Forms.DataGridViewRow r in MyGridView.Rows)
{
if ((r.Cells[5].Value).ToString().ToUpper().Contains(searchText.ToUpper()))
{
MyGridView.Rows[r.Index].Visible = true;
MyGridView.Rows[r.Index].Selected = true;
}
else
{
MyGridView.CurrentCell = null;
MyGridView.Rows[r.Index].Visible = false;
}
}
I hope I got your problem well
string whereClause = "ContactPerson=" +textbox.text;
(datagridview.DataSource as DataTable).DefaultView.RowFilter = whereClause;
You can use the dataGridView1.Rows[iIndex].Visible in order to filter a dataGridView in case you don't have a datasource. Whereas this may be very slow if the AutoSizeMode of the column widths is enabled. (At least I had this problem).
The solution was to turn the AutoSizeMode off temporarily, then filtering this way is quite fast:
for (int z = 0; z < dataGridView1.Columns.Count; z++)
{ // Disabled AutoSize Mode for all columns
dataGridView1.Columns[iRow].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
}
for (int iRow = 0; iRow <= dataGridView1.RowCount; iRow++)
{ // Filtering dataGridView1
bool bVisibleCondition = ...
dataGridView1.Rows[iRealRow].Visible = bVisibleCondition;
}
for (int z = 0; z < dataGridView1.Columns.Count; z++)
{ // Enable AutoSize Mode for all columns
dataGridView1.Columns[z].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
}

textbox auto complete (Multi Line)

I am making a auto suggestion / complete textbox in C#, i followed below link, but text box isnt showing the suggestions
How to create autosuggest textbox in windows forms?
//-------- Get all distinct description -----------------------------
OleDbCommand command = new OleDbCommand(Queries.qry16, Connection);
OleDbDataReader reader = command.ExecuteReader();
//--------- Storing ------------------------------------
while (reader.Read())
{
namesCollection.Add(reader.GetValue(0).ToString());
}
//----------- Close after use ---------------------------------------
reader.Close();
//----------- Set the auto suggestion in description box ------------
descriptionBox.AutoCompleteMode = AutoCompleteMode.Suggest;
descriptionBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
descriptionBox.AutoCompleteCustomSource = namesCollection;
Here is my code , it is in load function of winform. And the nameCollection initializtion is in constructor... kindly please help to make it working.
I am editing my post rather then creating new... I have tried the my own code in single line textbox and it worked. Now i want the same in multi line... For research i googled more then 2 days trying different codes (one with intelli sense) but it didnt worked as auto suggestion available in textbox. Can any one give me suggestion to code the whole procedure to multi line.. Thank you.
AutoCompleteSource does not work on multiline TextBox controls.
Wich means you need to make it from scratch:
I would make a ListBox to display the content of your autocomplete:
var listBox = new ListBox();
Controls.Add(listBox);
You need eventhandling on your textbox however this is a bit crude, so i would rewrite it to stop the keyupevent at some point:
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
var x = textBox.Left;
var y = textBox.Top + textBox.Height;
var width = textBox.Width + 20;
const int height = 40;
listBox.SetBounds(x, y, width, height );
listBox.KeyDown += listBox_SelectedIndexChanged;
List<string> localList = list.Where(z => z.StartsWith(textBox.Text)).ToList();
if(localList.Any() && !string.IsNullOrEmpty(textBox.Text))
{
listBox.DataSource = localList;
listBox.Show();
listBox.Focus();
}
}
Now all you need is a handler to set the text in your textBox:
void listBox_SelectedIndexChanged(object sender, KeyEventArgs e)
{
if(e.KeyValue == (decimal) Keys.Enter)
{
textBox2.Text = ((ListBox)sender).SelectedItem.ToString();
listBox.Hide();
}
}
Put in null checks where appropriate
You need to add a New Component class by 'Adding New Item'. and then write the code for that class and then add that component wherever required..
Try this code as it works in my case:
AutoCompleteStringCollection MyCollection = new AutoCompleteStringCollection();
while (reader.Read())
{
namesCollection.Add(reader.GetString(0));
}
reader.Close();
descriptionBox.AutoCompleteMode = AutoCompleteMode.Suggest;
descriptionBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
descriptionBox.AutoCompleteCustomSource = namesCollection;
con.Close();
Please check if the reader is getting the desired records..:)
Bit of confusion on the "auto-suggestion" since that is basically auto-complete without the permission from the user to "complete" the text. Nevertheless here are a couple of links you might find helpful:
http://docs.jquery.com/UI/Autocomplete
Autocomplete functionality on a textarea
AutoComplete extender for multi-line Textbox
Scroll down on link #2, a user suggested a jquery solution and compare with link #1. You may find a solution.
Third link is from asp forums, similar question like yours was also answered by a link. You might want to check that out.
Thismay help you solving problem ;
You can change table name. you can change the query to load listbox.
ListBox lbox;
private void IletisimBilgileriDoldur()
{
try
{
string strQuery= "Select adres From tblIletisimBilgileri Where adres <> '';";
veri = new OleDbCommand(strQuery,strConn);
veri.CommandType = CommandType.Text;
if (strConn.State == ConnectionState.Closed) strConn.Open();
oku = veri.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(oku);
oku.Close();
txtAdres.AutoCompleteCustomSource.Clear();
if (dt.Rows.Count >= 0)
{
lbox = new ListBox();
for (int count = 0; count < dt.Rows.Count; count++)
{
lbox.Items.Add(dt.Rows[count]["adres"].ToString());
}
}
txtAdres.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
txtAdres.AutoCompleteSource = AutoCompleteSource.CustomSource;
if (strConn.State == ConnectionState.Open) strConn.Close();
}
catch (Exception)
{
if (strConn.State == ConnectionState.Open) strConn.Close();
}
}
private void txtAdres_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
var x = txtAdres.Left;
var y = txtAdres.Top + txtAdres.Height;
var width = txtAdres.Width;
const int height = 120;
lbox.SetBounds(x, y, width, height);
lbox.KeyDown += lbox_SelectedIndexChanged;
lbox.DoubleClick += lbox_DoubleClick;
gbxAdres.Controls.Add(lbox);
lbox.BringToFront();
lbox.Show();
ActiveControl = txtAdres;
}
void lbox_DoubleClick(object sender, EventArgs e)
{
txtAdres.Text = ((ListBox)sender).SelectedItem.ToString();
lbox.Hide();
}

How can I retrieve all GridViewRows from a GridView control with paging enabled?

I am working on Add To Cart Functionality, and I have added a GridView control with paging enabled. In the GridView, I show the quantity in a text box and handle the OnTextChanged event for that textbox. Now the problem, is how can I keep the changed quantity text in session or view state, and in which row, so that I can update my GridView and bind that data again to the GridView?
Here I took GridView with id gvMaster.
protected void txtQuantity_TextChanged(object sender, EventArgs e)
{
gvMaster.DataSource = ProductDetailsGridMaster();
gvMaster.AllowPaging = true;
gvMaster.DataBind();
}
public DataTable ProductDetailsGridMaster()
{
DataTable dtProducts = new DataTable();
dtProducts.Columns.Add("ProductId");
dtProducts.Columns.Add("ProductName");
dtProducts.Columns.Add("ProductPrice");
dtProducts.Columns.Add("Quantity");
dtProducts.Columns.Add("Price");
gvMaster.AllowPaging = false;
if (Session["dtProducts"] != null)
{
GridView gv = new GridView();
gv.DataSource = Session["dtProducts"];
gvMaster.DataSource = gv.DataSource;
gvMaster.DataBind();
lblMessage.Text = "";
}
//GridView gvc = (GridView)Page.FindControl("gvMaster");
for (int i = 0; i < gvMaster.Rows.Count; i++)
{
Label lblProductId = (Label)gvMaster.Rows[i].Cells[0].FindControl("lblProductId");
Label lblProductName = (Label)gvMaster.Rows[i].Cells[1].FindControl("lblProductName");
Label lblProductPrice = (Label)gvMaster.Rows[i].Cells[2].FindControl("lblProductPrice");
//Label lblssno = (Label)gv.Rows[i].Cells[2].FindControl("lblSSNo");
TextBox txtQuantity = (TextBox)gvMaster.Rows[i].Cells[3].FindControl("txtQuantity");
//TextBox mastertxtQuantity = (TextBox)gvMaster.Rows[i].Cells[3].FindControl("txtQuantity");
Label lblPrice = (Label)gvMaster.Rows[i].Cells[4].FindControl("lblPrice");
var Price = decimal.Parse(lblProductPrice.Text) * decimal.Parse(txtQuantity.Text);
lblPrice.Text = Price.ToString();
DataRow dr = dtProducts.NewRow();
dr["ProductId"] = lblProductId.Text;
dr["ProductName"] = lblProductName.Text;
dr["ProductPrice"] = lblProductPrice.Text;
dr["Quantity"] = txtQuantity.Text;
dr["Price"] = lblPrice.Text;
dtProducts.Rows.Add(dr);
}
Session["dtProducts"] = dtProducts;
return dtProducts;
}
I want to show changed quantity value in grid with paging enabled.
I can hardly understand what your code really does. However, such information like the state of a control shouldn't be kept in Session. Use ViewState instead.
Add C# Asp.net tags to your question.
Also look up n-tier programming/mvc with asp.net , it will help you improve your code many folds

Categories

Resources