I want a comboBox to autocomplete and I found the below code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace testcomboBox
{
public partial class Form1 : Form
{
List<string> listOnit = new List<string>() { "Stephen_Curry", "Kevin_Durant", "Draymond_Green", "Zaza_Pachulia","Gerald Green" };
List<string> listSearchUpdate = new List<string>();
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listSearchUpdate.Clear();
foreach (var item in listOnit)
{
if (item.Contains(comboBox1.Text))
{
listSearchUpdate.Add(item);
}
}
comboBox1.Items.AddRange(listSearchUpdate.ToArray());
comboBox1.SelectionStart = comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
}
}
The code has a bug When type letter "G",the comboBox immediately autoselects "Gerald Green" and fills it to the edit control of the comboBox,but if you type "G" again,the edit control just fine to show "G" and pop up list of "Draymond_Green" and "Gerald Green". So how to disable autoselection function when type string in the edit control of the comboBox?
refer to this linkenter link description here
I revised code below and it is ok.
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
comboBox1.Items.Clear();
listSearchUpdate.Clear();
string strTemp = string.Empty;
foreach (var item in listOnit)
{
if (item.Contains(comboBox1.Text))
{
strTemp = comboBox1.Text;
listSearchUpdate.Add(item);
}
}
comboBox1.Items.AddRange(listSearchUpdate.ToArray());
comboBox1.DroppedDown = true;
comboBox1.SelectionStart = strTemp.Length;
Cursor = Cursors.Default;
}
Related
I have a simple WinForm with a DataGridView that shows record with Entity Framework.
My problem is that New Row feature appears only if the DataGridView is empty.
How is the problem?
Thank you in advance.
Luis
PS
Here some details of the WinForm class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GestioneFormazione;
namespace MpFormazione
{
public partial class MpFormazione : Form
{
public MpFormazione()
{
InitializeComponent();
this.dataGridView1.CellClick += DataGridView1_CellClick;
this.dataGridView1.AllowUserToAddRows = true;
this.dataGridView1.VirtualMode = true;
this.dataGridView1.AutoGenerateColumns = false;
}
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == this.ButtonColumunIndex)
{
if (e.RowIndex == 0)
{
Cliente cliente = new Cliente();
cliente.ID = Guid.NewGuid();
if (dataGridView1.Rows[0].Cells[1].Value != null)
cliente.Nome = dataGridView1.Rows[0].Cells[1].Value.ToString();
SaveToDb(cliente);
}
}
}
private void SaveToDb(Cliente cliente)
{
using (var context = new MPFORMAZIONEEntities())
{
context.Cliente.Add(cliente);
context.SaveChanges();
}
}
private void clienteBindingSource_CurrentChanged(object sender, EventArgs e)
{
}
private void ClienteBindingSource_AddingNew(object sender, System.ComponentModel.AddingNewEventArgs e)
{
}
private int ButtonColumunIndex
{
get
{
return 2;
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void MpFormazione_Load(object sender, EventArgs e)
{
using (var context = new MPFORMAZIONEEntities())
{
this.dataGridView1.DataSource = context.Cliente.ToList<Cliente>();
}
}
}
}
The page has only this code, and the Entity Framework for "Cliente" and "Dipendente" entities.
I want to covert the datagridview into an ini file after inputting the data.
http://www.hoons.net/Board/qacshap/Content/67073
When I enter the URL above,
I try to put data into the grid and press the export button to save it as an .ini file in the form of section, key, value. What should I do? Inside the code, the content is created as an ini file, but not as a grid.
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.Runtime.InteropServices;
using System.IO;
namespace EXPORT
{
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
[DllImport('kernel32')]
public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport('kernel32')]
public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
static string path = 'C:\\Test.ini';
public Form1()
{
InitializeComponent();
dataGridView1.AllowUserToAddRows =true; //자동 행 추가
dataGridView1.AutoGenerateColumns = false;
}
private void button1_Click(object sender, EventArgs e)
{
WritePrivateProfileString('SECTION', 'KEY', 'VALUE', #'C:\ConnectionInfo.ini');
MessageBox.Show('EXPORT successfully to *.INI format');
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void WriteInFile(string section,string key,string value,string path)
{
WritePrivateProfileString(section, key, value, path);
if (value == null)
{
throw new ArgumentException();
}
}
private void button2_Click(object sender, EventArgs e) //ADD_ROW Button
{
DataGridViewButtonColumn button = new DataGridViewButtonColumn();
{
dataGridView1.Rows.Add();
}
}
}
}
You can use my MadMilkman.Ini library for this, here is how:
private void button1_Click(object sender, EventArgs e)
{
IniFile iniFile = new IniFile();
IniSection iniSection = null;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (row.IsNewRow)
break;
string section = row.Cells[0].Value?.ToString();
string key = row.Cells[1].Value.ToString();
string value = row.Cells[2].Value.ToString();
if (!string.IsNullOrEmpty(section))
iniSection = iniFile.Sections.Add(section);
iniSection.Keys.Add(key, value);
}
iniFile.Save("C:\\Test.ini");
}
Also, here is how the generated "Test.ini" file looks like:
[a]
123=456
789=234
345=678
[b]
123=456
789=234
345=678
I am trying to click on "btnPunch". This button is located in an iFrame. I am unable to make this work. I have used the Selenium IDE to record this button being clicked and created a DLL that also runs this process in NUnit without a problem. Any help would be appreciated after three months of working on this.
Thank you
using System;
using System.IO;
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.Net;
using System.Threading;
using NUnit.Framework;
using Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium;
namespace TimeClockEntry
{
public partial class PNow : Form
{
IWebDriver driver = new InternetExplorerDriver();
//driver = new InternetExplorerDriver();
//private ISelenium selenium;
//private StringBuilder verificationErrors;
//public void SetupTest()
//{
// selenium = new DefaultSelenium("localhost", 4444, "*chrome", "https://ew23.ultipro.com/");
// selenium.Start();
// verificationErrors = new StringBuilder();
//}
int linkcount = 0;
string userName;
string passWord;
public PNow()
{
InitializeComponent();
webBrowser1.Navigate("https://ew23.ultipro.com/login.aspx");
}
private void PNow_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
userName = Properties.Settings.Default.userName;
passWord = Properties.Settings.Default.passWord;
}
private void PNow_FormClosed(object sender, FormClosedEventArgs e)
{
this.Hide();
welcome f1 = new welcome();
f1.ShowDialog();
this.Close();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
this.Focus();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
linkcount++;
if (linkcount == 1)
{
webBrowser1.Document.GetElementById("ctl00_Content_Login1_UserName").SetAttribute("value", userName);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_Password").SetAttribute("value", passWord);
webBrowser1.Document.GetElementById("ctl00_Content_Login1_LoginButton").InvokeMember("click");
}
if (linkcount == 2)
{
HtmlElement link = (from HtmlElement elem in webBrowser1.Document.GetElementsByTagName("a")
where elem.InnerHtml == "Time Clock Entry"
select elem).ElementAt(0);
link.InvokeMember("Click");
}
if (linkcount == 3)
{
// driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
this.Close();
}
}
}
}
You can try this also:-
if (linkcount == 3)
{
WebElement frameSwitch = driver.findElement(By.xpath("Xpath of iframe")); //Frame Xpath
driver.switchTo().frame(frameSwitch);
driver.FindElement(By.Id("btnPunch")).Click();
webBrowser1.Document.GetElementById("ctl00_Content_lnkLogout").InvokeMember("click");
driver.switchTo().defaultContent();
this.Close();
}
Try this.
if (linkcount == 3)
{
//get back to basic html source.
driver.SwitchTo().DefaultContent();
//switch to new frame
driver.SwitchTo().Frame("<FRAME NAME OR ID>");
driver.FindElement(By.Id("btnPunch")).Click();
}
So i'm making a basic yahtzee program i c#, and im trying to make an actual gui and not just use the console. However i have a problem with the textbox. When i roll the dice, i want the textbox to display the number rolled. Now it shows nothing. I use two classes, one for the actual program and one for handling the gui. This is the yahtzee class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Yahtzee
{
class YahtzeeScorer {
Random rndm = new Random();
Form1 gui = new Form1();
String dice1, dice2, dice3, dice4, dice5;
public void rollDice()
{
String a = Console.ReadLine();
this.dice1 = rndm.Next(1, 7).ToString();
this.gui.tbDice_SetText(this.dice1);
}
static void Main(String[] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
YahtzeeScorer ys = new YahtzeeScorer();
Application.Run(ys.gui);
ys.rollDice();
Console.WriteLine("The result was: " + ys.dice1 );
Console.Read();
}
}
}
And this is the gui class form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Yahtzee
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void tbDice_SetText(String s)
{
//this.ActiveControl = tbDice;
Console.WriteLine("SetText");
tbDice.Text = s;
}
public void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
tbDice is the name of the textbox component. Any ideas?
Examine the lines:
Application.Run(ys.gui);
ys.rollDice();
rollDice() will not be called until the application exits, because the thread running Main() will block on Application.Run() until it does.
Instead, try calling ys.rollDice() in something like a button event handler.
UPDATE
You are mixing your game logic and your presentation logic by putting both aspects in YahtzeeScorer. I would suggest that you move the game logic into a separate class like this:
public class YahtzeeGame
{
public string rollDice()
{
return rndm.Next(1, 7).ToString();
}
}
public partial class Form1 : Form
{
YahtzeeGame game = new YahtzeeGame();
public Form1()
{
InitializeComponent();
}
// You need to create a new Button on your form called btnRoll and
// add this as its click handler:
public void btnRoll_Clicked(object sender, EventArgs e)
{
tbDice.Text = game.rollDice();
}
}
I want to write a custom FrameworkElement which host Visuals. My first attempt was to create an instance of ContainerVisual and write a wrapper property for ContainerVisual.Children and then set it as ContentProperty so I can and Visuals via XAML. But VisualCollection does only implement ICollection and not IList or any supported interface and VisualCollection is selead so I can't implement IList on my own.
How can I hostvisuals and let them add declaratively using XAML?
Okay, long time ago but here is the solution I found that time back...
The Collection:
Note the hack comments.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Collections.ObjectModel;
using WPF.Controls.Primitives;
namespace WPF.Controls.Core
{
public class PrimitiveCollection : ObservableCollection<Primitive>
{
protected PrimitiveContainerVisual _owner;
public PrimitiveCollection(PrimitiveContainerVisual owner)
: base()
{
if (owner == null)
throw new ArgumentNullException("owner");
_owner = owner;
}
protected override void ClearItems()
{
foreach (var item in this)
{
item.IsDirtyChanged -= new IsDirtyChangedHandler(item_IsDirtyChanged);
_owner.InternalRemoveVisualChild(item);
}
base.ClearItems();
}
protected override void InsertItem(int index, Primitive item)
{
if (item != null && item.Parent != null)
throw new ArgumentNullException("Visual has parent");
item.IsDirtyChanged += new IsDirtyChangedHandler(item_IsDirtyChanged);
_owner.InternalAddVisualChild(item);
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
Primitive item = this[index];
item.IsDirtyChanged -= new IsDirtyChangedHandler(item_IsDirtyChanged);
_owner.InternalRemoveVisualChild(item);
base.RemoveItem(index);
}
protected override void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
}
void item_IsDirtyChanged(object sender, PrimitiveChangedEventArgs e)
{
if(e.IsDirty)
_owner.RequestRedraw();
}
}
}
And the Control which you can use in XAML
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using WPF.Controls.Primitives;
using System.Windows;
using System.Reflection;
namespace WPF.Controls.Core
{
public class PrimitiveContainerVisual : Visual
{
private PrimitiveCollection _primitives;
private PropertyInfo _contentBoundsPropInfo;
private PropertyInfo _descendantBoundsPropInfo;
public PrimitiveCollection Children
{
get { return _primitives; }
set { _primitives = value; }
}
public Rect ContentBounds
{
// HACK access internal property of Visual
get { return (Rect)_contentBoundsPropInfo.GetValue(this, null); }
}
public Rect DescendantBounds
{
// HACK access internal property of Visual
get { return (Rect)_descendantBoundsPropInfo.GetValue(this, null); }
}
public PrimitiveContainerVisual()
{
_primitives = new PrimitiveCollection(this);
Type thisType = this.GetType();
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
_contentBoundsPropInfo = thisType.GetProperty("VisualContentBounds", flags);
_descendantBoundsPropInfo = thisType.GetProperty("VisualDescendantBounds", flags);
}
internal void InternalAddVisualChild(Primitive prim)
{
this.AddVisualChild(prim);
}
internal void InternalRemoveVisualChild(Primitive prim)
{
this.RemoveVisualChild(prim);
}
public bool RequestRedraw()
{
UIElement uiParent = VisualParent as UIElement;
if (uiParent != null)
{
uiParent.InvalidateVisual();
return true;
}
else
return false;
}
}
}