ComboBox Items contains objects, which are pretty dumb. The first thing you should do is to create a class, maybe like this: class ComboItem { public string Text { get; set; } public int Level { get; set; } public ComboItem (string text, int level) { Text = text; Level...
I had a similar problem before. With the lasts version of windows you can't write directly to the LocalMachine emplacement due to security concern. They are no error because the key is created in another emplacement. Did you try searching for your key ? Try to execute your program in...
Well, you don't have enough code. Not so sure I'd recommend this, moving the "focus" from one value to another isn't exactly very intuitive. You'll get better UI from simply using two NUDs. Anyhoo, some code to play with: using System; using System.ComponentModel; using System.Windows.Forms; using System.Globalization; class RangeUpDown :...
c#,winforms,propertygrid,typeconverter
This is rather unusual as Plutonix commented, but here is a way to do it. Just use the following TypeConverter on the Members property. Since the PropertyGrid is based on properties, you have to create fake properties that represent each member. That's what represents the MemberDescriptor class here. public class...
If I understand the question correctly, you have a background worker thread that is executing code that can raise either of two different kinds of events for which you want to report progress. The ProgressChanged event handler in turn needs some way of updating the appropriate label for the given...
winforms,chromium-embedded,cefsharp
answer from Alex Maitland on Cefsharp google groups You can either load your own 'Loading Page' initially from local disk which is pretty fast. First approach is using a ResourceHandler (You can load a stream from disk). https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Example/CefExample.cs#L98 (You should also use a SchemeHandler, which gives a bit more flexibility...
This code doesn't actually print something, it's using the Shell to send a Print command to whichever program the user has installed to handle pdfs. This may or may not be Adobe Acrobat. The process will finish as soon as the verb is sent. It won't even wait until the...
c#,winforms,events,keypress,keydown
@Idle_Mind thanks. it works. Posting comment as answer: and I write this codes on Form1_Load The Load() event occurs before the form has been displayed, therefore your keystroke(s) is being sent to whatever application had focus right before your program was run (probably Visual Studio if you're running from...
You have to decide: Either maximize the form (which always makes sure the TaskBar is still visible) or set the dimensions manually. I suggest you remove the WindowState line. Another failsafe way would be to hide the TaskBar from your code, for example as described here....
This is the recommended pattern for implementing events. Each Event Foo has a corresponding protected method OnFoo. The method is responsible for triggering the event. (By default the designer will create event handlers named ctrl_Foo). This means that most of the time Event registration should be used, but there are...
How about: index1=_playList.Items.IndexOf(curItem); if(index1 >= 0) { _playList.SetSelected(index1, true); } ...
You need to use TryParse method. Actually what is happening is that when you enter some value it is being parsed correctly but when you press backspace that value is removed and textbox becomes empty so trying to convert an empty string into decimal gives format exception. Either you can...
I've used something like to read a user.config file using the built in XmlTextReader. But let me also say, that it seems like a bad design to couple your service and UI using a text file especially a user config file which in mind is susceptible to be filled with...
c#,excel,winforms,datagridview
See this question: How to bind a List<string> to a DataGridView control? In your case you are using a BindingList<string> but the logic is the same. The DataGridView is looking for object properties to bind, String however, only has the property length....
Here's what I would do: private async void ButtonClick() { //here, you're on the UI Thread button1.Enabled = false; await Task.Run(() => DoTheWork()); //you're back on the UI Thread button1.Enabled = true; } private void DoTheWork() { //this will be executed on a different Thread } ...
c#,.net,windows,winforms,sharpdevelop
Your program is looking for compas.ico inside the build directory, while it probably resides in some other directory in your project.
c#,excel,winforms,excel-2010,vsto
Ok I was able to fix the issue using the following code protected override void WndProc(ref Message m) { if(m.Msg == 528 && !this.Focused) { this.Focus(); } base.WndProc(ref m); } I added this function to my TaskPaneView which is simply a UserControl with that webbrowser child. I don't have a...
private void listBox1_KeyPress(object sender, KeyPressEventArgs e) { string letter = ""; //letter = ProcessKey(e.KeyChar); //or letter = e.KeyChar.ToString(); } private string ProcessKey(char key) { return key.ToString(); } ...
c#,.net,vb.net,winforms,datagridview
(Updated) You need to iterate the rows collection, test if each is selected, then swap rows. In order to keep 2 selected rows from swapping with each other when they get to the top or bottom, a separate Up and Down method are needed. ' list of hash codes of...
Your problem is caused by the error first pointed by HABO, however I wish to give also this answer because a ListBox.Items has a method called AddRange that can be used with a single line of code using Linq _playList.Items.AddRange(_openFile.FileNames .Select (fn => Path.GetFileName(fn)) .ToArray()); ...
c#,.net,sql-server,winforms,sqldependency
There's quite a few limitations with SqlDependency. To quote one relevant issue: The projected columns in the SELECT statement must be explicitly stated, and table names must be qualified with two-part names.Notice that this means that all tables referenced in the statement must be in the same database. (see https://msdn.microsoft.com/library/ms181122.aspx...
c#,winforms,datagridview,multi-select
In your GridNavigation method, under both conditions, if (keys == Keys.Enter || keys == Keys.Right) and else if (keys == Keys.Left), the guilty party here is the recurring line: dataGridView1.Rows[iRow].Cells[i].Selected = true; What went wrong? When dataGridView1.MultiSelect == false the above line effectively sets the current cell, not just the...
winforms,task-parallel-library
No need to worry; as soon as you create the delegate, all the objects it references will be kept in memory, at least until the Task.Run exits. There's nothing that an STA thread does that changes that. Threads don't factor into GC at all - except that all stacks for...
c#,.net,vb.net,winforms,custom-controls
If you want to get results that reliably look like the BorderStyles on the machine you should make use of the methods of the ControlPaint object. For testing let's do it ouside of a Paint event: Panel somePanel = panel1; using (Graphics G = somePanel.CreateGraphics()) { G.FillRectangle(SystemBrushes.Window, new Rectangle(11, 11,...
c#,html,winforms,diacritics,accented-strings
Only thing I can think of is specifically specifying your encoding on the file write, like: File.WriteAllLines(massagedFileName, linesModified, Encoding.UTF8); ...
select the label then goto autosize and set it to false... then increase the length of the label as much as you want... then apply your above code... it'll work.. All the best...
If you're generating the DataGridViews dynamically then you can use exactly the approach you propose. Instances of controls on a form are objects in C# like any other, so you can hold a reference to those objects in an array. Not knowing much of your code, this is a bit...
Assuming your full JSON is as you show, your JSON doesn't give simple name/value pairs for name and email. Instead it has a dictionary of indexed property objects, where each object has a label property with value equal to the name of property you seek, and an adjacent value property...
c#,winforms,entity-framework,orm
As strange as it sounds ,you don't have to dispose you DbContext (IF you haven't manually opened the connection yourself) Have a look at this: Do I always have to call Dispose() on my DbContext objects? Nope That said , I suggest that you use one context per method(and dispose...
The problem is you're trying to enable or disable the button when checking individual textboxes and they're conflicting with each other, instead the logic needs to be at a higher level. Change your textbox validation function to return a bool, and use that in ValidateAll to determine whether or not...
c#,winforms,if-statement,listbox
if (listBoxEmails.Items.Count >= 0 && listBoxWebsites.Items.Count >= 0 && listBoxComments.Items.Count >= 0) { //perform action } ...
The applicationName.exe.config file contains the application settings of your application and in case you have app.config file in you application, this file will be created. And if application is using these configurations, your application will break if you remove this file. To remove the .manifest file, you can go -...
But I don't know how to do this with RowLeave. Any suggestions? I can't find any examples or find it in the docs. I found the method in the docs but not how to register the event handler DataGridView has a RowLeave event property that you can subscribe to...
database,vb.net,winforms,textbox
I don't think you need to first query the db to get the count of records before then going back to the db to get the phonenumbers, you could just do this: mycom.CommandText = "SELECT Cellphone FROM tbl_applicant where Gender='Female';" myr = mycom.ExecuteReader While myr.Read() TextBox1.Text = TextBox1.Text & myr(0)...
c#,.net,winforms,youtube,youtube-api
You're trying to call a v2 URL (the one that starts with https://gdata), which no longer exists. Additionally, the location you got a developer key from is also deprecated; you won't use a "developer key," but the API key you get from console.developers.google.com -- NOT the client ID, though. You...
c#,.net,winforms,user-interface
Thanks to Idle_Mind, his advice about using UserControls (which I hadn't heard of until he pointed out) helped me dissect the problem into smaller parts and figured out that the size of a panel has to absorb its controls, so according to the answer of that question, I used a...
You could define a variable which goes to true when you press the button and check on close if the variable is true e.g. private bool btnClicked = false; public void btnChallenge_Click(object sender, EventArgs e) { btnClicked = true; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if(btnClicked) { e.Cancel=true;...
c#,winforms,ms-word,word-interop
You can use the Find object of an empty (or indeed any) Range to set the bounds of the range to a particular word/string in the document: Word.Range range = document.Range(0, 0); if (range.Find.Execute("<table>")) { // range is now set to bounds of the word "<table>" } The Execute method...
c#,multithreading,winforms,datagridview
You have to keep your workers in order to stop them. Save them in a dictionary with the identifier of the row as a key: Dictionary<string, BackgroundWorker> workers = new Dictionary<string,BackgroundWorker>(); Then, for each worker you need to add the handler for the RunWorkerCompleted event in which you remove the...
I have found a workaround. If you do Me.ShowIcon = False after the form is loaded, then it will display in the taskbar, but not on the program. One way to do this is to have a timer enabled/begin as soon as form load ends, and then on tick, do...
java,c#,winforms,spring-mvc,spring-security
Authentication can be setup in many ways with Spring Security. For example: <http pattern="/webservice/**" create-session="stateless" realm="TestRealm"> <http-basic/> <intercept-url pattern="/**" access="ROLE_USER"/> </http> Then it is as simple as this to authenticate from C#: var request = (HttpWebRequest)WebRequest.Create(url); request.Credentials = new NetworkCredential(username, pwd); ...
Create a new instance of ComboboxItem each time you want to add a new item to the combo box: for (int i = 0; i < result.Items.Count; i++) { ComboboxItem item = new ComboboxItem(); item.Text = result.Items[i].Snippet.Title; item.Value = result.Items[i].Id; comboBox1.Items.Add(item); } ...
This is rather simple for any control including TabControls and TabPages but not Forms. All you need to do is enlarge the relevant controls enough to show all their content. (They don't have to be actually visible on screen.) Here is an example: tabControl1.Height = 10080; tabPage2.Height = 10050; dataGridView1.Height...
winforms,powershell,button,click,action
If you want to toggle the action of the button each time the button is clicked, you need to replace the current action with the other action within each action: $actionAll = { # other operations here $OKButton.Text = 'None' $OKButton.Remove_Click($actionAll) $OKButton.Add_Click($actionNone) } $actionNone = { # other operations here...
winforms,visual-studio-2013,c++-cli
Don't hard-code the desktop directory name, it is not c:\users\desktop. .NET makes it easy: String^ path = System::IO::Path::Combine( Environment::GetFolderPath(System::Environment::SpecialFolder::Desktop), DateTime::Now.ToString("yyyyMMddhhmmss")); System::IO::Directory::CreateDirectory(path); // Write file(s) to <path> //... It is up to you to decide how fine-grained to make the directory name, if you do this at a very high rate...
There are various amounts of trouble you'll get into when you hang-up the UI thread like this. This is certainly one of them, nothing pleasant happens when the user wildly bangs on the button to try to get something noticeable to happen. And sure, those clicks won't get lost, they...
This should do the trick instead of Delete and AcceptChanges: Form1.dt.Rows.RemoveAt(i); Update: Caution when using a DataAdapter and relational data source along with your DataTable. Using Remove modifies the DataTable, but not the actual data source. See https://msdn.microsoft.com/en-us/library/03c7a3zb(v=vs.110).aspx...
Why don't you just calculate the sum of your "point" labels at the end of both events? It is nice and simple(You could do it more efficiently but i don't this there is a reason... ) Just call TotalPoints() at the end of checkBox_CheckedChanged,txtBox_CheckedChanged int TotalPoints() { int total =...
For some reason neither setting the LineWidth works nor making the LineColor = Color.Transparent, which usually works fine for Chart elements. But you can set it to have the same Color as the Chart's BackColor: chart1.ChartAreas[0].AxisX.LineColor = chart1.BackColor; To remove a few ore things you can write this: chart1.ChartAreas[0].AxisX.MajorGrid.Enabled =...
You should set KeyPreview property of the form to true. By setting this property the form will receive key events before the event is passed to the control that has focus. In your form constructor this.KeyPreview = true; ...
Assuming PaymentTypeID - PaymentTypeName is 1-to-1, you could change your group by to this: group CashTransactions by new { PaymentTypeId = PaymentTypes.Field<Int32>("cashpaymenttype_id"), PaymentTypeName = PaymentTypes.Field<String>("cashpaymenttype_name") } into GroupPaymentTypes The your select will look like this: select new { cashpaymenttype_id = GroupPaymentTypes.Key.PaymentTypeId, cashpaymenttype_name = GroupPaymentTypes.Key.PaymentTypeName, ... } ...
c#,multithreading,winforms,async-await
Using the comments on my question, especially the note about the continuation method which made me find this very useful question, I achieved the following: The first part of initialization is performed asynchronously (no change). The second part of the initialization (which creates the UI elements) is performed afterwards as...
.net,vb.net,winforms,datagridview,datatable
what can I do to manage a DataSource instead of directlly manage the rows collection of the control A Class and a collection are pretty easy to implement as a DataSource and will also it will be pretty easy to modify your MoveUp/Dn methods for it. Class DGVItem Public Property...
The attributes you're trying to get aren't attribute of Payments element. You need to go one level deeper to get them. Try this way : ...... doc = XDocument.Load(reader); var data = doc.Root .Elements() .Elements("Payments"); foreach(var d in data) { var patti = d.Element("Patti"); list1.Add(new List<string>() { patti.Attribute("Rent").Value, patti.Attribute("Water").Value, patti.Attribute("Electricity").Value,...
c#,winforms,textbox,windows-forms-designer,form-control
In C# Window application, control values are render after event is executed. After your click event textbox is displaying last value that is updated. If you want to render text-box value during event execution.You have to call refresh method of text-box to render value. Use this.. You have to refresh...
c#,.net,multithreading,winforms
The ProgressChanged is a message system intended to get messages from the background worker thread to the calling thread. Since you have access to this plumbing, I would put the code in the ProgressChanged event by defining a message. You can pass multiple types of messages and arguments using this...
c#,winforms,applicationcontext
The compiler thinks appForm is a Form and not an AppForm because of the way you're declaring it: Form appForm; Either try changing the declaration to AppForm appForm; or cast it like: ((AppForm)appForm).someToolStripMenuItem.Click += form_Click; ...
That's what a SplitContainer is for. It has two panels splitted horizontally or vertically (property Orientation) The user has then the ability to resize both panels. Insert a SplitContainer and dock it fully in the parent form. (Dock = DockStyle.Fill) Insert another two SplitContainers in each panel of the top...
Your View and Model should be independent of each other and the Presenter. They may live in their own projects, but it would be fine in a simple program for everything to be in the same project. If you do want them in separate projects, that is easily done. The...
You can avoid the multiple prompts by checking to see if Application.Exit() has been called already from within the FormClosing event: void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason != CloseReason.ApplicationExitCall) { DialogResult dialog = MessageBox.Show("Are you sure you want to really exit ? ", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialog...
Use a bool flag and a TimeSpan and a counter for the seconds until the next clearing: DateTime startTime = DateTime.Now; TimeSpan elapsed = new TimeSpan(0); bool running = true; int clearInSeconds = 300; private void Clock_Tick(object sender, EventArgs e) { // function one: count elapsed running time if (running)...
The issue was the thread. Somehow C# knew that I was calling the SFD from an exiting routine even when I started another thread. I ran everything from a timer task routine with a flag to turn the SFD on/off and everything ran perfectly. Thanks for all the help everyone.
You have three parameters in your second command (command2) - but you never define those parameters, nor do you set any values for them to use! Try this code: string command1 = "SELECT Column1, Column2, Column3 FROM Table1"; string command2 = "UPDATE Table2 SET Column2 = @var2, Column3 = @var3...
_NullFlags is a private field that is used by the dbf to keep track of which fields can have a Null value. If you really don't want it, try adding a not null after every field: Best N(5) not null, Aanb N(5) not null, ... ...
There's PropertyGrid: var form = new Form(); form.Controls.Add ( new PropertyGrid() { SelectedObject = new { A = "Hi", B = new [] { 32, 40 } } } ); form.Show(); It's quite far from how the debugger one works, but it can be quite easily modified to handle any...
Call ReadToEnd before WaitForExit Chris' code: private void button1_Click(object sender, EventArgs e) { /*Relevant Code*/ Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = String.Format("/k cd {0} && backdoor -rt -on -s{1} -p{2}", backdoorDir, pSN, sPPC); p.Start(); string result =...
You need a function like that? ShowWhatIWant(true, false, false); private string ShowWhatIWant(bool showMinutes, bool showSeconds, bool showMiliSeconds) { string text = string.Format("{0:00}", Math.Floor(elapsed.TotalHours)); if(showMinutes) { text += string.Format(":{0:00}", elapsed.Minutes); } if(showSeconds) { text += string.Format(":{0:00}", elapsed.Seconds); } if(showMiliSeconds) { text += string.Format(":{0:00}", elapsed.Milliseconds); } return text; } ...
vb.net,multithreading,winforms
The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of...
Reset the DialogResult value for the btnAdd control back to None, and try setting the value of the DialogResult in your code, when you know the form can be successfully closed: private void btnAdd_Click(object sender, EventArgs e) { try { iD++; this.GetEmployee = new Employee(iD, txtFirstName.Text, txtLastName.Text, txtEmail.Text); this.DialogResult =...
There are two options: Designing a Form inside the Visual Studio Designer and open a new instance of this inside your code Create a new form and add elements (Labels, ...) inside your code 1: Form2 frm2 = new Form2(); frm2.Open(); 2: Form aForm = new Form(); aForm.Text = "Title";...
c#,winforms,events,user-controls
You need to loop through each page of the tab control. Winforms only loads a tab page when it is first visited for(int i=1; i < tabControlName.TabPages.Length; i++) tabControlName.SelectedIndex = i; tabControlName.SelectedIndex = 0; Changing the selected index will make the tab pages load....
What you are looking for is probably the Control.PointToScreen method: Computes the location of the specified client point into screen coordinates. The inverse is the Control.PointToClient method, by the way....
How can i display it as MB's instead of Bytes ? If you bit shift a number every 10 you do will be a unit in size larger so 10 is Kb, 20 is Mb, 30 is Bytes, and so on. So if you divide your number by 1...
If the databound item does not contain notify property changed events, the user interface (datagridview) won't know anything has changed. You'll have to trigger the refresh manually. Either the entire grid or source or something like dataGridBasket.InvalidateRow(row.Index)
c#,multithreading,winforms,text,file-io
You've got multiple problems here, the use of the File is probably not thread-safe. your method does not repeat your are Sleep()ing on a Thread You can solve all of them by ditching the Thread and use a simple Timer. ...
don't use DialogResult property of form for comparison. Set it only on successful close private void dgvSomeGrid_DoubleClick(object sender, EventArgs e) { string name = dgvSomeGrid.CurrentRow.Cells[5].Value.ToString(); var result = MessageBox.Show(name, "Select this Merkmal?", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { _someID = Convert.ToInt32(dgvMSomeGrid.CurrentRow.Cells[0].Value.ToString()); this.DialogResult = DialogResult.Yes; this.Close(); } } ...
You could write your own method for showing form and throwing event in him. public event EventHandler ShownEx; public void ShowEx() { Show(); OnShownEx(); } private void OnShownEx() { var eventHandler = ShownEx; if (eventHandler != null) eventHandler(this, EventArgs.Empty); } ...
c#,forms,winforms,user-interface,user-controls
You're never calling your FrmLogin.Frm method. If you intend this to be a constructor, drop the void and rename it to FrmLogin, like so: public FrmLogin() { this.Size = new Size(400, 600); Button btn = new Button(); btn.Text = "Something"; btn.Size = new Size(10, 10); btn.Location = new Point(10, 10);...
You need some sort of data structure to store prior ellipses. One possible solution is below: private List<Ball> balls = new List<Ball>(); // Style Note: Don't do this, initialize in the constructor. I know it's legal, but it can cause issues with some code analysis tools. private void pbField_Paint(object sender,...
Look at this line: new UploadTestingForum().Run().Wait(); Remember that this is part of your form's constructor. When that code runs, it creates another instance of the form and runs its constructor. At that point you'll execute this same code again, which creates another instance and runs its constructor, which executes this...
vb.net,winforms,visual-studio-2010
Here's a method that will detect only letters but there is far more to your problem than just that. Private Function IsAllAlpha(text As String) As Boolean Return text.All(Function(ch) Char.IsLetter(ch)) End Function Notice that I have written a Function rather then a Sub. Your original method is poorly written. What you...
c#,winforms,validation,currency,tryparse
See Find number of decimal places in decimal value regardless of culture to find the number of decimal places. Just verify that it's <= 2. e.g. decimal value = 123.456m; if (GetDecimalPlaces(value) > 2) { // Error } int GetDecimalPlaces(decimal d) { int count = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2]; } ...
c#,winforms,gdi,renderer,toolstrip
All the stock ToolStripItems you can add with the designer already render their own background. So what you draw with your OnRenderItemBackground() override is immediately over-painted again. So ProfessionalToolStripRender simply doesn't override the method since nothing needs to be done. The base class method, ToolStripRender.OnRenderItemBackground(), doesn't do anything either. Note...
Well, the way you are reporting is a bit unusual to say the least. But if I try to follow your pattern, then your backgroundWorker1_ProgressChanged will probably want to change to something like this: private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { int eventIndex = (int)e.UserState; if (eventIndex == 0) //...
Use the RowEnter event: private void DataGridView1_RowEnter(object sender,DataGridViewCellEventArgs e) { btnUpdate.Enabled=!DataGridView1.Rows[e.RowIndex].Cells[10].Value.ToString().Equals("Completed") ; } Perhaps, the following is required just after having filled the gridview (I don't remember if the RowEnter event is raised or not at initialisation). btnUpdate.Enabled=DataGridView1.CurrentRow!=null && !DataGridView1.CurrentRow.Cells[10].Value.ToString().Equals("Completed") ...
c#,.net,multithreading,winforms,.net-3.5
When you call MainForm.Invoke you're telling the form to schedule the operation provided to be run from the application loop the form is running in. When you're calling that method your form has no application loop, and as such there's nothing to run the operation that you've scheduled, so it...
vb.net,winforms,visual-studio-2012
Forms comes as partial class meaning the code is separated in two files. The "empty" code you shown is from "mcastmain.vb" (if the file is named as the class). With that one there is a (probably hidden) file "mcastmain.designer.vb" file which contains the generated code by the designer ; and...
You simple need to pass references from the different forms that you want to call from another form. Or depending on how the application works you keep a reference of the form you created. That way you can call in any direction depending on the how the dependency really is....
AppendText will just append the text to the end, which isn't what you want. Instead, you must find the text you want to replace and select it. Once it is selected, you can overwrite it. This is a full example. The Form sets its RichTextBox to say "Hello", my name...
Refer this code: private bool draging = false; private Point pointClicked; private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (draging) { Point pointMoveTo; pointMoveTo = this.PointToScreen(new Point(e.X, e.Y)); pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y); this.Location = pointMoveTo; } } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { draging = true;...