This question already has an answer here:
I have this:
string t = "<";
This will give me < Now i want to add to it one Quotation mark " So the string will be <"
This question already has an answer here:
I have this:
string t = "<";
This will give me < Now i want to add to it one Quotation mark " So the string will be <"
chartarea.CursorX.SetCursorPixelPosition(cursor_point, true);
This line consume a lot of CPU resource.
Especially when there are several ChartAreas.
How can I reduce the cpu usage when setting cursor lines to the chartareas?
I'm using winforms ToolTip class on a DataGridView (not tooltip of datagridview since I need custom formatting.)
And I call toolTip.Show() in DataGridView's CellMouseEnter event.
toolTip.Show() shows the the tooltip immediately and InitialDelay property is not working since I called toolTip.Show().
Is there another way to delay toolTip.Show() just like regular initaldelay.
I'm amazed how difficult this seems to be. I 'just' want to print my form (it's an invoice), and ensure it prints the whole form (not just what is displayed on the screen)? I can alter anything I want on the form itself..so how do I set it all up so it prints perfectly to a standard letter sized sheet of paper, and doesn't let the user resize it, etc etc. They should see it just like it will print.. maybe they can zoom in and out, but no re-sizing, etc.
I thought a reportviewer control would be handy in order to handle all the printing and sizing stuff.. but that control doesn't seem to lend itself to a single record display. (maybe have a Header as the entire report! seems crazy)
so unless i'm wrong, maybe someone can just give me all the properties to set, etc, in order to make a regular form statically sized for a standard sheet of paper (8.5 x 11)? And then show me the way to print the entire thing rather then just a 'printscreen'.
I've read a bunch of ideas for using 'printscreen' and using GDI+ (i didn't fully understand how I could use that).. nothing seems to be standing out for me.
I am using Devxpress 12.2.7, in ver 14, if I set the parameter visible = false then they will not be asked for entering. Now, in version 12.2.7, I set visible = false, passed value to them, but the parameter still be ask to enter.
This is the startup state of Printcontrol, the values is passed before, not by typing
I have asked this question a couple of days ago and really did not get any help on it. So i am going to re-ask the question in a more better sense. I am doing a fully automated speech recognition program. I have the program complete but one error. This error happens to be the InitializingComponent(). see code below:
public frmMain()
{
InitializeComponent();
in the program i have 2 winforms (using C#) that uses the same events and methods. Once i do the Form frmEdit, I then can change the class name to all the same for example this is the breakdown:
public partial class frmMain : Form public partial class AlarmClock : Form public partial class Commands : Form
ok i originally changed Form1 : Form to frmMain : Form. this form contains all the events, methods, constructors etc., etc.,
With the Form Edit option i can edit the form names. So i changed the other two with the same public partial class name. So now all three are frmMain : Form.
However i have no errors anywhere in the program except this error that is on the frmMain (Form1) and the error says:
Error 1 The call is ambiguous between the following methods or properties: 'Ivan.frmMain.InitializeComponent()' and 'Ivan.frmMain.InitializeComponent()' C:\Users\Ian\Desktop\Ivan Assistant\Ivan\Ivan\Form1.cs
I have pasted the exact error. So i have done this program before, then scratched it and started over and so forth.
What do i need to do to correct this error. If you need to see more code then i can make a video and post it on youtube for you to see. I really don't want to start all over again but that is neither there nor here. This program is eventually going to be going out for testing once i can get this error resolved and see if it will debug.
This is about as plain as i can explain this with out the ability to post pictures at the moment. But like i said i can do a video and explain what i am doing. If that would help anyone.
I am trying to write a simple winform app that gets an xml file with image urls and shows the images: Here is an xml:
<catalog>
<product>
<imageurl>http://ift.tt/1DmECW9;
<product>
<product>
...
<product>
</catalog>
I'm using a backgroung worker for this taks so my code looks like this:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
XmlNodeList xnList = doc.SelectNodes(...);
foreach (XmlNode product in xnList)
{
PictureBox img = new PictureBox();
img.Dock = System.Windows.Forms.DockStyle.Fill;
img.Location = new System.Drawing.Point(3, 28);
img.Size = new System.Drawing.Size(194, 94);
img.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
//img.LoadAsync(product[...].InnerText);
img.Load(product[...].InnerText);
}
}
When I use the img.LoadAsync
I don't see any image and when I'm getting up to image number 1990 out of 8700 and the I'm getting this exception:
An exception of type 'System.ComponentModel.Win32Exception' occurred in
System.Windows.Forms.dll but was not handled in user code
Additional information: Error creating window handle.
When I'm using img.Load
I sometimes get the image and sometimes I get timeout exception...
This is not a difficult task to do and yet, how can I have a simple code that works ?
I am using the System.Windows.Forms.WebBrowser to display XML. If i load the XML into the Control by default the elements are completely expanded. The user can collapse them manually to the depth/level that he wants.
Is it possible to collapse the elements to a certain depth/level with C# code. Let's say the XML elements are expanded to a depth of 2 or 3 and all the below elements are collapsed?
The thread that I tried is the below one, but it did not solve my problem completely.
collapse all elements for loaded xml in webbrowser control using c#
I am losing my mind a little bit here. When I initially build up a ListView, it works totally as expected:
ListViewItem listViewItem = listView.Items.Add(model.Id.ToString(), model.Name, model.Id.ToString());
listViewItem.SubItems.AddRange(new ListViewItem.ListViewSubItem[]
{
new ListViewItem.ListViewSubItem() {Name = "ArtNr", Text = model.ArticleNumber},
new ListViewItem.ListViewSubItem() {Name = "Quantity", Text = "XXX"},
});
I have 3 columns defined in the control, and they display, respecively, Name, ArticleNumber and "XXX", to begin with.
At a later stage, I have to replace "XXX" with actual data, and do the following:
foreach (ListViewItem listViewItem in listView.Items)
{
InvoiceLine invoiceLine = FindInvoiceLine(...);
if (invoiceLine == null)
continue;
listViewItem.SubItems["Quantity"].Text = invoiceLine.Quantity.ToString();
}
I can see the Text actually being set in the proper SubItem.Text, also if I check later, while referencing the listview through a different reference, i.e. I know I am looking at the right object. However GUI does not reflect the change, it still says "XXX" in the 3rd column.
What gives?!
My application is hardware based so it have connection in first form's contructor called myform. i want to display splash screen until loads myform in background. application in c sharp. after splash screen login will display.
I have a gridview. In addition to the standard column that are being displayed in the gridview, I want to capture unique data about some rows in the same gridview.
For example I want to link object XYZ with row #10. Also, I want to link object ABC to row #11 while row #1-9 does not have any objects linked to them but they have standard column information.
namepace RM
{
public class XYZ{
public string serialNum;
public string serviceLevel;
}
public class ABC{
public string insurancePlan;
public string phoneNumber;
}
}
how can I link the objects to a specific?
The way I have my application coded is "if a row has typeColumn == 'Electronic'
then I display a form that captures the information for the object XYZ. "If a row has typeColumn == 'Insurance'
then I display a form that captures the information for the object ABC.
How do I
INSERT
into the database? my question is how to read the data not how to insert the data into the database.I have a problem with DataGridView in WindowsForms Application created in VS 2013. Application works with no exceptions in Debug build, but when I switch to Release build, and try to click on datagridview cell I have an exception:
Exception:Thrown: "Index -1 does not have a value." (System.IndexOutOfRangeException) A System.IndexOutOfRangeException was thrown: "Index -1 does not have a value." Time: 2015-02-28 19:19:29 Thread:[13944]
Here is the code which do the stuff:
private void dgvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dgvList.Refresh();
var senderGrid = (DataGridView)sender;
if (e.RowIndex >= 0)
{
if (senderGrid.Columns[e.ColumnIndex].Name == "Delete")
{
Book b = (Book)dgvList.CurrentCell.OwningRow.DataBoundItem;
ArrayOfBooks.Remove(b);
fillGV();
}
}
}
private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
dgvList.Refresh();
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex].Name == "Author" && e.RowIndex >= 0)
{
Book b = (Book)dgvList.CurrentCell.OwningRow.DataBoundItem;
frmAuthors frmAuth = new frmAuthors(b);
frmAuth.mainForm = this;
frmAuth.Show();
}
}
What is more in that app I have second form with very similar code and it works well. I found answer for similar question(here) but it doesn't help me.
I have a inherited button which I use in a Winform application that uses a tooltip control. All is good with the tooltip, but it appears that the base class button in showing a tooltip along with the parent. I would like to disable the base class button from showing it's tooltip while preserving the tooltip for the parent. I wanted to post the picture showing the dual tooltip, but too much a nubie here, I am sure your imagination see what is see...if not let the force guide you.
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace GUI
{
public partial class ToggleButton : Button
{
private Button button;
[Category("Behavior")]
[Description("Gets or sets the botton state")]
[DefaultValue(true)]
public bool State { get; set; }
[Category("Behavior")]
[Description("Gets or sets the TRUE state text")]
public string TrueText { get; set; }
[Category("Behavior")]
[Description("Gets or sets the FALSE state text")]
public string FalseText { get; set; }
public ToggleButton() : base(){}
private void InitializeComponent()
{
this.button = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button.Location = new System.Drawing.Point(0, 0);
this.button.Name = "button";
this.button.Size = new System.Drawing.Size(75, 23);
this.button.TabIndex = 0;
this.button.Text = "button";
this.button.UseVisualStyleBackColor = true;
this.button.Click += new System.EventHandler(this.button2_Click);
this.ResumeLayout(false);
}
private void button2_Click(object sender, EventArgs e)
{
Button clickedButton = (Button)sender;
State = !State;
clickedButton.Text = State ? TrueText : FalseText;
}
}
}
How do I use FlowLayoutPanel to display multiple PictureBox controls, where each PictureBox, has 3 relatively positioned TextBox controls nested inside?
I am making a mailing label printing application.
I needed to dynamically display labels to be printed by using a FlowLayoutPanel. It is easy to see how to use FlowLayoutPanel to display multiple PictureBox controls, and I really like the way the layout is handled.
Is this a case for a custom control? Is there a way to control the position of the Textbox controls relative to the parent PictureBox? Do I extend my MailingLabel Class to include the visual components of the mailing label as it is displayed in the form?
Need some general guidance.
On a C# Winform how do I stop the user moving the mouse outside the active boundary of the winform? So I do not want the cursor to move out side the form boundary until they have completed an action that will close the winform. Any ideas of answers please?
I am trying to bind a GridView using a BindingList<T>
in an MVVM pattern.
In my code, I bind the gridview as follows:
BindingSource bindingSource = new BindingSource(Context.MyList, null);
bindingSource.CurrentChanged += Context.BindingSourceCurrentItemChanged;
// NOTE: this part is to test if the event is fired...
Context.MyList.ListChanged += myList_ListChanged;
myGrid.DataSource = bindingSource;
I have an add button that calls a method in the Context as an ICommand
:
Context.myCommand.Execute(null);
Finally, in the command itself (which is in the Context class), I do the following:
MyList.Add(new Item());
Pretty straight forward implementation... The bindingSource.CurrentChanged
does fire properly, but I never enter the myList_ListChanged
event.
If I stop on the launching of the ICommand
and add several items, the Context.MyList
count is indeed updated. Same occurs with if I use delete command...
Is there anything obvious I am missing here ???
Thanks in advance, N.
EDIT I realized that for the problem comes from the fact I have MyList as a property as follows:
BindingList<T> myList;
public BindingList<T> MyList {
get {
if (myList == null) { myList = new BindingList<T>();}
return myList;
}
}
I create the BindingSource
in the form's constructor, whereas I have the following code called in the ViewModel AFTER the binding is made:
myList = new BindingList<T>
RaisePropertyChanged("MyList");
I know this is WPF thinking, where this would update data bindings seamlessly.
As I understand this, BindingSource
doesn't seem to listen to the changes of the datasource itself (i.e. the pointer to the object), as opposed to changes of its content.
Would anyone be kind enough to confirm this behavior? Thanks! N.
here is what I am trying to accomplish. I want to make an application with two forms. A login form and the main form that is displayed after login. The login form will allow the user to add his details and store them into a file for the next time he opens the app. When the user successfully logs, he does not have to write those details anymore. The next time he opens the application the main form is displayed right away. So, when the user opens the app, the two forms are originally hidden (minimized / notintaskbar). The application will check if settings file is there and attempts to login then displays the main form if its successful. If it cannot read / login the login form is displayed. Now, here is my question. how do I implement this efficiently.
Originally, I have started the login form as the entry point in main.cs. The logic is handled and if the login is successful it displays the second form. Though, if I close the login form at this point it will close the application since its the entry point. So, I could get around this by hiding the login form and continuing with the main form. Though, I do not like the approach. So, I went ahead and made the main form the entry on main.cs. I would call the login form which will handle the check (settings/login) and do it like mentioned. Though, when I display the hidden main form and attempt to close the login form (from within the login form). It causes the application to close. I am trying a third approach now where I handle the logic on main form and call the login form with showdialog instead of show. Then, I would do the logic on login and return only if I am successful.
I just want to know what is the most efficient approach to accomplish what I am trying to do. Thanks.
i'm working on a project for school and have some logical errors. I have 2 different forms: frmOrders and frmCustomers. frmOrders is the main form and when i click a button here, frmCustomers will show. There is a datagrid named txtTable in frmCustomers.
Now, what i want to do is when I double click a row, some of the info goes in some textboxes in frmOrders then frmCustomers closes. Also, i want the rest of the controls in frmCustomers to be disabled. (I have set the access modifiers for the controls in frmCustomers as public but it does't seem to work.) How do I do that?
Currently this is my code:
public partial class frmOrders : Office2007Form
{
public frmOrders()
{
InitializeComponent();
}
private void frmOrders_Load(object sender, EventArgs e)
{
}
private void btnCustomer_Click(object sender, EventArgs e)
{
frmCustomers c = new frmCustomers();
c.ShowDialog();
c.txtAddress.Enabled = false;
c.txtBday.Enabled = false;
c.txtContactNo.Enabled = false;
c.txtFname.Enabled = false;
c.txtLname.Enabled = false;
c.txtMI.Enabled = false;
c.txtSearch.Enabled = false;
c.btnDelete.Enabled = false;
c.btnSave.Enabled = false;
c.btnUpdate.Enabled = false;
}
}
I have a c# windows form project with the following c# code which uses BiQuadFilter class of NAudio library to implement low pass filter. The problem I am facing is that the intensity of the sound is also dropping along with the frequency thus making the volume barely audible. How can I fix this?
My Code:
private ISampleProvider sourceProvider;
private BiQuadFilter[] filters;
private int channels,cutOffFreq;
//Constructor
public MyFilter(ISampleProvider sourceProvider,int cutOffFreq)
{
this.sourceProvider = sourceProvider;
this.cutOffFreq = cutOffFreq;
channels = sourceProvider.WaveFormat.Channels;
filters = new BiQuadFilter[channels];
CreateFilters();
}
private void CreateFilters()
{
for (int n = 0; n < channels; n++)
if (filters[n] == null)
filters[n] = BiQuadFilter.LowPassFilter(44100, cutOffFreq, 1);
else
filters[n].SetLowPassFilter(44100, cutOffFreq, 1);
}
public WaveFormat WaveFormat { get { return sourceProvider.WaveFormat; } }
public int Read(float[] buffer, int offset, int count)
{
int samplesRead = sourceProvider.Read(buffer, offset, count);
for (int i = 0; i < samplesRead; i++)
buffer[offset + i] = filters[(i % channels)].Transform(buffer[offset + i]);
return samplesRead;
}
This is how I am using it:
waveOut.Init(new MyFilter(new AudioFileReader(path + "\\Audio_Tracks\\" + topic + "\\" + currentTrack + ".wav"), 750));
waveOut.Play();
I'm using an HTML text editor control hosted within a visual Studio winform.
It is based on MSIE. How can I ensure spellcheck applies to the entire body of a web page?
I have on my screen 1 line, and this line has 8 text fields. All text fields have a unique name, for example:
address1
, phone1
, comment1
, time1
, timer1
, call1
, person1
, delivery1
I want to make these names to be dynamically names so that I can produce more text field (in button off the first line) automatically by pushing a button. How can I make the names of dynamic objects like names automatically added to the name, for example: address (1), address (2), ... address (x) ..., etc.
The form needs to function and look like an Excel form. I am using Visual Studio 2013 and write code in VB.
Public Class Form1
Dim TextdCount1 As Integer = 1
Dim TextitCount1 As Integer = 1
Dim d(10) As String
Dim it(10) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'הקוד של הכפתור
Dim TextdName1 As String = "d" & TextdCount1
Dim TextitName1 As String = TimeOfDay
'משתנה בשם textboxname1
'שווה לטקסט ו מספר שבשמתנה textboxcount1
If TextdCount1 <= 5 Then
CreateNewTextBox(TextdName1, TextdName1, 25, 50, 10, TextdCount1 * 25 + 10)
TextdCount1 += 1
'60 אורך התיבה
'25 + 10 הפרשי הגובהה בין התיבות
CreateNewTextBox(TextitName1, TextitName1, 60, 50, 40, TextitCount1 * 25 + 10)
TextitCount1 += 1
End If
End Sub
Private Sub CreateNewTextBox(ByVal Name As String, ByVal Text As String, ByVal Width As Integer,
ByVal Height As Integer, ByVal Left As Integer, ByVal Top As Integer)
Dim TextBox1 As New TextBox With
{
.Name = Name,
.Text = Text,
.Width = Width,
.Height = Height,
.Left = Left,
.Top = Top
}
Me.Controls.Add(TextBox1)
AddHandler TextBox1.TextChanged, AddressOf TextBox_TextChanged
d(0) = TextBox1.Text
Dim TextBoxit1 As New TextBox With
{
.Name = Name,
.Text = Text,
.Width = Width,
.Height = Height,
.Left = Left,
.Top = Top
}
Me.Controls.Add(TextBoxit1)
AddHandler TextBoxit1.TextChanged, AddressOf TextBox_TextChanged
it(0) = TextBoxit1.Text
End Sub
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs)
Dim TextBox1 As TextBox = DirectCast(sender, TextBox)
d(0) = TextBox1.Text
End Sub
Private Sub TextBoxit1_TextChanged(sender As Object, e As EventArgs)
Dim TextBoxit1 As TextBox = DirectCast(sender, TextBox)
it(0) = TextBoxit1.Text
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
MsgBox("d = " + d(0))
MsgBox("in time = " + it(0))
End Sub
End Class
so now, the 1 text box is d1 (its id and going to be d1, d2, d3 and act) the 2 text box need to save the time, now when save the value off d to d(0) and the value off time to it(0) when i press the button to show the value off d(0) and it(0) its show me just the it(0) 2 time. what i doing Wrong? Thanks for all your help :)
I'm currently developing an app that uses System.Diagnostics.Process
to get the Window Title of the Current Active App or the App on the ForeGround. Now, this is fine and working with the current code I have until I came across with this issue. This NullReferenceException
occurs if I switch my app using the task bar icon instead of the minimized button of the app window.
Originally I used this
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
To get what I need. But I'm still having the same issue when switching app using the task bar icon. The only difference with using this code is that the exception is this A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll
My operating system is Windows 8.1.
Any inputs is greatly appreciated.
Best regards
I have this code:
string firstTag = "Forums2008/forumPage.aspx?forumId=";
string endTag = "</a>";
index = forums.IndexOf(firstTag, index1);
if (index == -1)
continue;
var secondIndex = forums.IndexOf(endTag, index);
result = forums.Substring(index + firstTag.Length + 12, secondIndex - (index + firstTag.Length - 50));
The string i want to extract from is for example:
<a href="/Forums2008/forumPage.aspx?forumId=317" title="הנקה">הנקה</a>
What i want to get is the word after the title only this: הנקה
And the second problem is that when i'm extracting it i see instead hebrew some gibrish like this: ������
I need to make a simple virtual keyboard gui program in C# that functions as a spell checker. Not as in, I click the "s" key and it inputs "s" into the text box; but rather, while I'm typing, the on-screen keyboard highlights each letter as I press it. It's supposed to be for people who are learning how to type so they don't need to look down at their keyboard.
Can someone familiar with C# help me figure out how to make a button (or if you can suggest something better than a button) highlight upon keypress? To be more specific, can you point me in the right direction to get an event handler in place for each button to "highlight" for every keypress on the keyboard? Once I get that, I think I can get the spell-checker coding out of the way.
I'm using Visual Studio. Here's a screen shot. Both text boxes are rich text boxes, the top is set to "read-only", and that is the text that needs to be entered. The "keyboard" underneath is just composed of buttons.
Thank you in advance!
I have a problem, I want to add an item using datareader in the datagridview which is I can only add once and if I add another one it'll error. Here's my codes:
connect = new OleDbConnection(coo); connect.Open();
command.Connection = connect;
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter("SELECT * FROM Items where itemno = '" + textBox1.Text + "'", connect);
ODA.Fill(dt);
command.CommandText = "SELECT * FROM Items";
OleDbDataReader reader = command.ExecuteReader();
object[] obj = new object[256];
while (reader.Read())
{
reader.GetValues(obj);
if ((textBox1.Text == obj[0].ToString()))
{
if (dataGridView1.DataSource == null)
dataGridView1.DataSource = dt;
else
((DataTable)dataGridView1.DataSource).Merge(dt);
int sum1 = 0;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
sum1 += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
}
textBox2.Text = sum1.ToString();
break;
}
else if (textBox1.Text==null)
{
break;
}
}
reader.Close();
connect.Close();
The error appeared as "Input string was not in a correct format" at the sum1 += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);... All I want is the items that I want to add at the datagridview have their prices and will add it all in the datagridview which is the total is in the textbox. plz help me guys..
I have a progressBar1 in the designer. And i have a loop that i'm reporting the progress but only the user state not the int.
while (index != -1)
{
string firstTag = "<div class=\"CatLinkContainer\">";
string endTag = "\" href";
index = forums.IndexOf(firstTag, index1);
if (index == -1)
continue;
var secondIndex = forums.IndexOf(endTag, index);
result = forums.Substring(index + firstTag.Length + 12, secondIndex - (index + firstTag.Length - 50));
if (result.Contains("forumPage"))
{
int index2 = result.IndexOf("\" href=\"http://ift.tt/1vHpBkn");
result = result.Remove(index2);
System.Threading.Thread.Sleep(1000);
countResults++;
backgroundWorker1.ReportProgress(0, result);
forumsNames.Add(result);
}
index1 = index + 1;
}
The reporting of the result is working fine. But now i'm reporting to the progressBar1 0. I want to calculate somehow the progress and report also to the progressBar1 the percentages.
I added countResults variable int and i did countResults++;
For example in this case there are 33 result items to report the question is how do i calculate so it will get to the 100% ? In other cases could be 1 items to report or 122.
In the backgroundworker progresschanged event i did:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripStatusLabel1.Text = e.UserState.ToString();
toolStripProgressBar1.Value = e.ProgressPercentage;
}
The UserState reporting is working fine. But now how do i calculate to report the ProgressPercentage ?
Im in winforms and trying to make a tileengine in it for school reasons. I have a trouble with drawing the tileset in the Panel. It's instead drawing in the top left of the Form and behind the Panel.
This is the code:
private void gfxPanel_Paint(object sender, PaintEventArgs e)
{
using (Bitmap sourceBmp = new Bitmap("../../assets/art/Tileset5.png"))
{
Size s = new Size(level.TileWidth, level.TileHeight);
Rectangle destRect = new Rectangle(Point.Empty, s);
for (int row = 0; row <= level.MapHeight; row++)
for (int col = 0; col < level.MapWidth; col++)
{
PictureBox p = new PictureBox();
p.Size = s;
Point loc = new Point(level.TileWidth * col, level.TileHeight * row);
Rectangle srcRect = new Rectangle(loc, s);
Bitmap tile = new Bitmap(level.TileWidth, level.TileHeight);
Graphics G = Graphics.FromImage(tile);
G.DrawImage(sourceBmp, destRect, srcRect, GraphicsUnit.Pixel);
p.Image = tile;
p.Location = loc;
this.Controls.Add(p);
}
}
}
Whats going on here and what am I doing wrong?
I have a RichTextBox and I wanna append a link inside, with arbitrary text, like this.
I found something to make it (http://ift.tt/1qNb2Y5) but I can't use it because I'm already using DotNetBar's RichTextBoxEx, and I can't replace it.
Any ideas ?
Thanks in advance.
My listbox control is Firing the SelectedIndexChange event when only the bound field DisplayMember is changed. I would expect the SelectedItem Changed event to fire, but this thing is firing the IndexChanged , is it "rebinding" because the bound field is changing and therefore causing the Index to be reset ?
DisplayMember = "MyField"; ValueMember = "MyID"; Datasource = MyBindingSource;
The selectedIndexEvent does fire when the selection changes too, it just should not fire when the DisplayMember changes.
This question already has an answer here:
I am trying to pass a username into a label in a windows form application from a login however it says Object reference not set to an instance of an object
in lblWelcome it says null but in the string msg it says the right logged in username why is this happening?
login:
i initialize it in the public part of the login
string msg;
then this is the if ssuccessul login
int i = ds.Tables[0].Rows.Count;
if (i == 1)
{
msg = "Welcome " + txtUsername.Text;
this.Hide();
Welcome f2 = new Welcome(msg);
f2.Show();
ds.Clear();
}
formwelcome
public Welcome()
{
InitializeComponent();
}
public Welcome(string msg)
{
InitializeComponent();
lblWelcome.Text = msg;
}
So I have been busy working on an assignment lately, now I'm programming in Visual Basic, Using Visual Studio 2013 Update 4, and I'm working in the .NET Framework.
Here's my problem/question: What I want to accomplish is that I run through an array of 81 (length) consisting of only characters. I want to iterate through this array and after 9 steps of my for-loop I want to save those 9 characters into a string.
With this I mean I want to save characters 0-8 in a string, then 9-17 in another string, and so on…
(Array will be filled in my program)
Dim charactersArray(81) as character
For intIndex as integer = 0 to 81
'Add 9 characters into a string
Next
I have tried a-lot to accomplish this but have failed to find a solution yet, I have searched all over the internet but I couldn't find a solution. So hopefully anybody here can help me out. :D
(Pretty much I'm asking you to make a little algorithm for me :/ )
I have 2 solutions in this project. A windows forms solution and a Windows 8.1 Tablet project. This is what's supposed to happen:
I'm storing the byte array like this:
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
Size aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
var readStream = fileStream.AsStreamForRead();
byte[] pixeBuffer = new byte[readStream.Length];
await readStream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);
}
The byte array is successfully stored in my database.
I'm running into a problem when converting the byte array into a WinForms Image. This is my code:
using (var ms = new MemoryStream(bytes))
{
Image i = Image.FromStream(ms);
return i;
}
This gives me an invalid parameter exception.
I'm guessing it's something with the image format? I'm really new to streams though so I have no idea.
Any help is welcome!
PS: I know storing in the SQL database runs perfectly since I can store and load images perfectly using the WinForms application only.
I'm working in project A, and I want to open Form F from Project B. I know that you can import B to project A and do B.FormF().Show()
, but this is very inefficient because I have to import the whole project into my other project.
So, my question is if there is an other and more efficient way to do this.
It may be a stupid question...but how can I make a Windows Form to load from the Bottom of the screen in VB.NET? I have tried using Form Location but it only have Center Screen ETC. :( Also tried this code...but not exactly what I would like..
Dim x As Integer
Dim y As Integer
x = Screen.PrimaryScreen.WorkingArea.Width - 400
y = Screen.PrimaryScreen.WorkingArea.Height - 270
Me.Location = New Point(x, y)
I'm Making a App that runs In Maximized Mode so it fills the whole screen. I want the app to have its own keyboard (a form with buttons that acts like keys!) that have to appear at the bottom (like the keyboard appears on the bottom of the screen at any Android / IOS Phone
I have a Dictionary<uint, string>
and a ComboBox
using the style DropDownList
, where I bind this dictionary, like:
comboBox1.DataSource = new BindingSource(myDic, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
Now I would like to be able to select an arbitrary item of my dictionary with a button click, so given the bound dictionary items:
Dictionary<uint, string> myDic = new Dictionary<uint, string>()
{
{ 270, "Name1" },
{ 1037, "Name2" },
{ 1515, "Name3" },
};
I have tried:
comboBox1.SelectedItem = myDic[270];
comboBox1.SelectedText = myDic[270];
comboBox1.SelectedValue = myDic[270];
comboBox1.SelectedItem = 270;
comboBox1.SelectedValue = 270;
But none of the above changed the selected item.
How can I change my current selected item by either the key or value of my datasource?
In this method i want to make the report:
private int reportingmethod()
{
if (result.Contains("forumPage"))
{
toolStripStatusLabel1
int index2 = result.IndexOf("\" text");
result = result.Remove(index2);
Names.Add(result);
}
}
I want to report the value in the variable result.
In backgroundworker dowork event:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
reportingmethod();
}
And a button click event that start the backgrounworker:
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Then in the background progress changed event i did:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
toolStripStatusLabel1.Text = e.Result.ToString();
}
First i'm not sure getting the Result like i did in the progress changed event is the right way.
Second how do i pass the result from the Do Work event ?
And third how do i report the result value from the reportingmethod ?
I never used before this toolStripStatusLabel with backgroundworker.
When I add an item to the datagridview (from another form), it shows up just fine. But when I try to add another item to the datagridview, only the new item appears, and the previous one gets thrown out, it appears.
Note that I'm using .Hide, and .Show, to move between two forms (add_form and main_form). I've tried using .ShowDialog to see if it would fix the problem, but instead I get multiple instances of the same window open after moving back and forth between forms.
How can I fix this problem?
Another complex one, I have searched everywhere and have only been able to find answers to 'how do i find a string in a combo box'
I want to know the opposite. I have a combo box filled with cities (strings) and I am passed an address string.
I would like to search my address string to see if it contains any one of the cities currently in my combo box.
eg. Combo box contains: London, Paris, Berlin
Addresses passed in:
I was thinking along the lines of
address.Contains(combobox.Any().ToString());
but as you can probably tell, that doesnt work!
I would like to create a application walkthrough for users to reveal functionality and give a short introduction to the software like this: http://ift.tt/1w2B0a9 This is often used for smartphone apps or browser applications. I've never seen this for Windows applications before, but this should be possible or not?
The application is implemented in C# and WinForms and uses a lot of controls from Infragistics.
It isn't possible to find anything about that on google or SO because "walkthrough" could be anything... :/ Maybe I'm looking for the wrong keywords?
I've created a .net program that essentially takes in a bunch of user options, then it passes these options into a 3rd party .dll through an xmlstring. My issue im having is taking my user data and inserting into into my XMLstring. Some example of my xml,
XmlString.Append(" <Input>");
XmlString.Append(" <ID>ReqInp_DrivenSpeed</ID>");
XmlString.Append(" <Value>875</Value>");
XmlString.Append(" </Input>");
This Xml is provided by the 3rd party, all i can change is the value, 875. I attempted to do it like this,
XmlString.Append(" <Input>");
XmlString.Append(" <ID>ReqInp_DrivenSpeed</ID>");
XmlString.Append(" <Value>" + textbox1.SelectedText.Tostring() + "</Value>");
XmlString.Append(" </Input>");
I thought this would work as its similar to what you can do with SQL, however, I'm getting no results back. Also the value entered into the textbox is 875, as its already a value accepted by the 3rd party app.
I am trying to upload a file via a POST to a REST API in a c# winform.
If I run the following command with curl the file is uploaded successfully:
curl.exe -H "Content-type: application/octet-stream" -X POST http://myapiurl --data-binary @C:\test.docx
I have tried using WebClient in my WinForm:
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "application/octet-stream");
byte[] result = client.UploadFile(url, file);
string responseAsString = Encoding.Default.GetString(result);
tb_result.Text += responseAsString;
}
But I just get a (500) Internal Server.
Checking this with fiddler the following headers are added with CURL:
POST http://myapiurl HTTP/1.1
User-Agent: curl/7.33.0
Host: 10.52.130.121:90
Accept: */*
Connection: Keep-Alive
Content-type: application/octet-stream
Content-Length: 13343
Expect: 100-continue
But checking my WebClient method shows the following:
POST http://myapiurl HTTP/1.1
Accept: */*
Content-Type: multipart/form-data; boundary=---------------------8d220bbd95f8b18
Host: 10.52.130.121:90
Content-Length: 13536
Expect: 100-continue
Connection: Keep-Alive
How can I simulate the CURL command above from my app?
I am using VS 2005 C#, working on an unfinished WinForm.
I have parsed an XML to a treeview listing but I'm encountering some problems. I wanna know if there's a way to hide/filter/remove a certain node containing a "_this_text" in its name without having to depend on a textbox.
This is what I have for the program (kudos to those who helped me develop this):
#region "***** XML Parsing *****"
private void Form1_Load_1(object sender, EventArgs e)
{
// Initialize the controls and the form.
//label1.Text = "File Path";
textBox2.Text = Application.StartupPath + "\\Continental.vsysvar";
//button6.Text = "XML";
//this.Text = "Software Validation";
}
private TreeNode selectedNode = null;
private void button6_Click(object sender, EventArgs e)
{
try
{
// SECTION 1. Create a DOM Document and load the XML data into it.
XmlDocument dom = new XmlDocument();
dom.Load(textBox2.Text);
// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();
/*treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = treeView1.Nodes[0];*/
foreach (XmlNode node in dom.DocumentElement.ChildNodes)
{
if (node.Name == "namespace" && node.ChildNodes.Count == 0 && string.IsNullOrEmpty(GetAttributeText(node, "name")))
continue;
AddNode(treeView1.Nodes, node);
}
treeView1.ExpandAll();
}
/* catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}*/
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void LoadTreeFromXmlDocument(XmlDocument dom)
{
try
{
// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();
// SECTION 3. Populate the TreeView with the DOM nodes.
foreach (XmlNode node in dom.DocumentElement.ChildNodes)
{
if (node.Name == "namespace" && node.ChildNodes.Count == 0 && string.IsNullOrEmpty(GetAttributeText(node, "name")))
continue;
AddNode(treeView1.Nodes, node);
}
treeView1.ExpandAll();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
static string GetAttributeText(XmlNode inXmlNode, string name)
{
XmlAttribute attr = (inXmlNode.Attributes == null ? null : inXmlNode.Attributes[name]);
return attr == null ? null : attr.Value;
}
private void AddNode(TreeNodeCollection nodes, XmlNode inXmlNode)
{
if (inXmlNode.HasChildNodes)
{
string text = GetAttributeText(inXmlNode, "name");
if (string.IsNullOrEmpty(text))
text = inXmlNode.Name;
TreeNode newNode = nodes.Add(text);
XmlNodeList nodeList = inXmlNode.ChildNodes;
for (int i = 0; i <= nodeList.Count - 1; i++)
{
XmlNode xNode = inXmlNode.ChildNodes[i];
AddNode(newNode.Nodes, xNode);
}
}
else
{
// If the node has an attribute "name", use that. Otherwise display the entire text of the node.
string text = GetAttributeText(inXmlNode, "name");
if (string.IsNullOrEmpty(text))
text = (inXmlNode.OuterXml).Trim();
TreeNode newNode = nodes.Add(text);
}
}
#endregion
And here's an excerpt of the XMl file since it's quite long:
<?xml version="1.0" encoding="utf-8"?>
<systemvariables version="4">
<namespace name="" comment="">
<namespace name="_01_Test_Preparation" comment="">
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_02_Shipping_Status_Check" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_02_Shipping_Status_Check_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_01_Get_Dem_ID" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_01_Get_Dem_ID_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_04_ECU_Version_Check_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_03_Test_Run_Init" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_04_ECU_Version_Check" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_05_DEM_Reader" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_03_Test_Run_Init_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_05_DEM_Reader_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
</namespace>
What I really want to accomplish is to hide or filter the nodes containing this text "_start" found in their name. So all nodes containing "_this_start" in their name would be hidden from the user. I've read that it is not technically possible to enable or disable visibility but instead gray out the text and whatnot.
Thank you in advance.
Recently I got an assignment to make a very basic Sudoku-game in Visual Basic. To make this I am using Visual Studio Ultimate 2013 Update 4 with the .NET Framework.
I have gotten to the point where I can check which one out of many textboxes has focus. With this also change the backgroundColor of the corresponding textbox. I have done this using this by using this method:
Private Sub TextBox_GotFocus() Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus Me.ActiveControl.BackColor = Color.Aquamarine End Sub
To Color it back to white when any of the textboxes lost focus I used this:
Private Sub TextBox_LostFocus() Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus Me.ActiveControl.BackColor = Color.White End Sub
Now My Questions Are:
(It Gives a NullReferenceException when being closed)
My plan is to get or set condition of textbox inside WebBrowser..
this is what iam trying :
If WBrowser.Document.GetElementById("searchbox").Focus = True Then
Dim XKeyboard as New FrmVKeyboard
XKeyboard.ShowDialog
Exit Sub
End If
But, this line make an error..
WBrowser.Document.GetElementById("searchbox").Focus = True
"Expression does not produce a value"
How can i get or set condition the textbox inside WebBrowser..
I have a windows form which lets the user to edit information in a database. I was wondering whether it would be possible to have like a button on an ASP.NET page like, "Run Editorial" and it will link to the windows form solution and run the form?
I'm trying to find some help in the ways of "Initializing" A module/Variable inside the module on an event.
I need it to load, in order for the following WinForm to use it (apparently) Let me explain...
I am using the WinSCP library and gotten plenty of help in the ways of WinSCP by the author himself. But in order to fix my current problem, I need to Initialize a Global Variable. So the Variable is there, its in order, but "Form2" refuses to use it, as it apparently needs to be Started/Initialized from an event in Form1. Module is called Public Module Module 1.
Public Module Module1
Public mySession As Session
End Module
I need to Launch/Start it on this Event;
Private Sub Loginbutton_Click(sender As Object, e As EventArgs) Handles Loginbutton.Click
WinSCP Author was unable to help as it was outside WinSCP alone, and just .Net/VB issue. I've gotten so much excellent help here on Stackoverflow so I know someone here will be able to help.
It might be some easy thing I have overlooked and forgotten. My head is hurting at this time, so any help, code samples and other forms of help is greatly appreciated as my head is slightly hurting of all this Visual Studio stuff.
I'm trying to find some help in the ways of "Initializing" A module/Variable inside the module on an event.
I need it to load, in order for the following WinForm to use it (apparently) Let me explain...
I am using the WinSCP library and gotten plenty of help in the ways of WinSCP by the author himself. But in order to fix my current problem, I need to Initialize a Global Variable. So the Variable is there, its in order, but "Form2" refuses to use it, as it apparently needs to be Started/Initialized from an event in Form1. Module is called Public Module Module 1.
Public Module Module1
Public mySession As Session
End Module
I need to Launch/Start it on this Event;
Private Sub Loginbutton_Click(sender As Object, e As EventArgs) Handles Loginbutton.Click
WinSCP Author was unable to help as it was outside WinSCP alone, and just .Net/VB issue. I've gotten so much excellent help here on Stackoverflow so I know someone here will be able to help.
It might be some easy thing I have overlooked and forgotten. My head is hurting at this time, so any help, code samples and other forms of help is greatly appreciated as my head is slightly hurting of all this Visual Studio stuff.
how can i change the color of the text which is being edited. i have a datagridview with values inside. what i want is when the user edit the text inside the cell. it must change the text to red how can i do that?
private void Gridview_Output_CellFormatting_1(object sender, DataGridViewCellFormattingEventArgs e)
{
if (Gridview_Output.Columns[e.ColumnIndex].Name == "FontOut")
{
Gridview_Output.Rows[e.RowIndex].Cells[3].Value = "FontOut";
DataGridViewCellStyle Cstyle = new DataGridViewCellStyle();
Cstyle.ForeColor = Color.Red;
}
}
I am using VS 2008 SP1 with some updates, doing SW development in C++/CLI and Winforms. I have one winforms probject, where the designer shows a failure upon opening:
HRESULT E_FAIL has been returned from a call to a COM component
bei EnvDTE.CodeFunction.get_FunctionKind()
bei Microsoft.VisualC.CppCodeParser.OnTypePopulateMembers(Object sender, EventArgs e)
bei System.CodeDom.CodeTypeDeclaration.get_Members()
bei System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
bei System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
bei Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
bei System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad(IDesignerLoaderHost host)
I can click on "ignore" then and see my whole winforms, being displayed correctly. But I don't want to ignore always, as it is 1) annoying, and 2) I would also ignore real failures, causing corruption on the form during design time (have had that some times before, loosing hours of development time)...
Another winforms project inside the same solution has no designer problems.
What I have tried so far:
What 'solves' the problem:
Any other ideas, how I can remove that failure? It's in VS obviously, as I can compile and run without errors, and even view the form on another VS as described above.
But I want to keep my original VS solution and not open another one.
There is a datagridview in my application where a scroll bar is being created at runtime. I need to make some modification to the scroll bar (need to make it shorter to position a page-up page-down bottom on top and bottom of the bar)
having a difficult time finding the sourcecode where the scroll bar gets created. I went into debugging mode to find that out however it is like a ghost and it shows up when gridview populates.
Any Help or information is appreciated.
I want to programmatically select multiple nodes in my RadTreeView from Telerik
component in a C# application. It's a winform.
I've set MultiSelect
property to True
. But when I try this:
myTree.SelectedNodes= someNodeCollection;
It says:
SelectedNodes has no setter
Is there a way to do this programmatically?
I have a WinForm application that I would like to add a RadDoc like a popup menu on the left inside form main.
The user should be able to hover to the left side of the screen or click some tab on the left side of the screen and then the menu bar will appear.
The RadDock control itself does not have a auto hide.
I can hide the ToolWindow inside the RadDock but this leaves a blue background where the ToolWindow would show.
Also, when the ToolWindows are "AutoHide" they are tabbed at the bottom but they need to be tabbed vertically on the left.
The last thing is that I can't seem to set the "popup" size of the ToolWindows.
In Winform,is there any way to enable radGrid Filtering only when Enter key pressed. because I want to filter records from server side (filter from total records in database). And also need to disable the auto-suggest text from filter control.
I added
this.radGridView1.FilterChanged += new GridViewCollectionChangedEventHandler(radGridView_FilterChanged);
But this event triggering without hit enter key. Its possible in web application. But Is there any option available in telerik for Winforms, or how can i do it.
thank you in advance!
Not sure why I'm getting this error, I had a look online but couldn't find a solution that worked, any ideas?
I am attempting to search for user's via products, so I enter in a product name and the user's full name and address will be output to a listbox, when I type in a product, however, I get this error:
Missing ), ], or Item in query expression '(((CustomerAccountDetails.custFullName) = 'Red Apple''.
I asked a question previously about the same program which helped a lot with my syntax but I guess I'm still not quite there, I'm still learning SQL so sorry if it is something really simple! :)
Dim searchDatabase As OleDbCommand = New OleDbCommand("SELECT CustomerAccountDetails.custFullName, CustomerAccountDetails.custAddress " _
& "FROM (CustomerAccountDetails " _
& "INNER JOIN CustomerTransaction ON CustomerAccountDetails.ID = CustomerTransaction.custID) " _
& "INNER JOIN (StockDescription " _
& "INNER JOIN TransactionDetails ON StockDescription.ID = TransactionDetails.stockID) ON CustomerTransaction.ID = TransactionDetails.custTransID " _
& "WHERE(((CustomerAccountDetails.custFullName) = '" & productSearch & "'", databaseConnection)
Dim searchResults As OleDbDataReader = searchDatabase.ExecuteReader
I'm using winforms ToolTip class on a DataGridView (not tooltip of datagridview since I need custom formatting.)
And I call toolTip.Show() in DataGridView's CellMouseEnter event.
toolTip.Show() shows the the tooltip immediately and InitialDelay property is not working since I called toolTip.Show().
Is there another way to delay toolTip.Show() just like regular initaldelay.
Following this SO answer, I'm doing:
ThreadPool.QueueUserWorkItem(
delegate
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
});
My goal is to do a garbage collection run after I close a large WinForms form with lots of images/PictureBox controls to ensure I have no images in memory anymore. (I do believe I follow the instructions of Jon Skeet).
I'm doing it in a background thread in order to try to have my UI responsive.
My question:
Does it bring me any benefits to do the garbage collection in a background thread? Or does it actually make my application slower/hang longer?
I want to use a WebBrowser-Control in a Winforms (.net / C#) application to show PPT and PPTX files. When I call Navigate() a download dialog appears (which is strange because its a local file).
webBrowser1.Navigate(fileName,false);
I also tried to canel the NewWindow - event but the Download-Dialog still shows up.
What am I missing?
Cheers!
Here my habits in my C#/WinForm applications
First a model.
public class MyModel : NotifyPropertyChangedAdapter
{
private string _propertyA;
private string _propertyB;
public string PropertyA
{
get { return _propertyA; }
set
{
// If nothing new just leave.
if (Equals(_propertyA, value)) return;
_propertyA = value;
OnPropertyChanged("PropertyA");
}
}
public string PropertyB
{
get { return _propertyB; }
set
{
// If nothing new just leave.
if (Equals(_propertyB, value)) return;
_propertyB = value;
OnPropertyChanged("PropertyB");
}
}
[...]
}
Lets use it in a UserControl
public partial class MyUserControl : UserControl
{
private MyModel _myModel;
public MyUserControl()
{
InitializeComponent();
}
[CanBeNull]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MyModel MyModel
{
get { return _myModel; }
set
{
// If nothing new just leave.
if (Equals(_myModel, value)) return;
// Unregister previous model.
if (_myModel != null)
{
_myModel.PropertyChanged -= MyModelOnPropertyChanged;
}
_myModel = value;
// Yep I have child user control who show stuffs depending of 'MyModel'.
childUserControl.MyModel = value;
// Register new model.
if (_myModel != null)
{
_myModel.PropertyChanged += MyModelOnPropertyChanged;
}
// Update UI stuffs which depends on MyModel
UpdateLabelA();
UpdateLabelB();
}
}
private void MyModelOnPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
{
switch (eventArgs.PropertyName)
{
case null: // I forget those two often
case "":
UpdateLabelA();
UpdateLabelB();
break;
case "PropertyA":
UpdateLabelA();
break;
case "PropertyB":
UpdateLabelB();
break;
}
}
private void UpdateLabelA()
{
// Yes, the model can be accessed by non-UI threads.
if (InvokeRequired)
{
Invoke((MethodInvoker) UpdateLabelA);
return;
}
// Take a local copy.
// Yes, the 'MyModel' properties can be changed by non-UI threads.
var myModel = MyModel;
if (myModel == null) return;
// Lets apply the so special formating.
labelA.Text = String.Format("A is: {0}", myModel.PropertyA);
}
private void UpdateLabelB()
{
if (InvokeRequired)
{
Invoke((MethodInvoker) UpdateLabelB);
return;
}
var myModel = MyModel;
if (myModel == null) return;
labelB.Text = String.Format("B is: {0}", myModel.PropertyB);
}
}
My point is : it is really too much verbose. In the ChildUserControl
there is exactly the same code for the MyModel
property.
And that is the simplest stuff I use. In general the MyModel
class are stored in a MetaModel
. For example I want to be able to switch from a model to an other.
The meta-model
public class MyMetaModel
{
private readonly MyModel _myModel1;
private readonly MyModel _myModel2;
private readonly MyModel _myModel3;
private int _currentMode;
private MyModel _currentModel;
public MyMetaModel()
{
// Initialize the models.
_myModel1 = new MyModel();
_myModel2 = new MyModel();
_myModel3 = new MyModel();
// Initialize current mode.
_currentMode = 1;
_currentModel = _myModel1;
}
public int CurrentMode
{
get { return _currentMode; }
set
{
if(Equals(_currentMode, value)) return;
if ((value < 1) || (value > 3)) throw new ArgumentException();
_currentMode = value;
switch (value)
{
case 1:
CurrentModel = _myModel1;
break;
case 2:
CurrentModel = _myModel2;
break;
case 3:
CurrentModel = _myModel3;
break;
}
}
}
/// <summary>
/// Gets the CurrentModel.
/// To change it, use <see cref="CurrentMode"/>.
/// </summary>
public MyModel CurrentModel
{
get { return _currentModel; }
private set
{
if (Equals(_currentModel, value)) return;
_currentModel = value;
OnCurrentModelChanged(EventArgs.Empty);
}
}
public event EventHandler CurrentModelChanged;
protected virtual void OnCurrentModelChanged(EventArgs eventArgs)
{
var handler = CurrentModelChanged;
if (handler == null) return;
handler(this, eventArgs);
}
}
Lets use it in the UserControl
public partial class MyUserControl : UserControl
{
private MyMetaModel _myMetaModel;
private MyModel _myModel;
public MyUserControl()
{
InitializeComponent();
}
[CanBeNull]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MyMetaModel MyMetaModel
{
get { return _myMetaModel; }
set
{
if(Equals(_myMetaModel, value)) return;
// Unregister previous meta-model.
if (_myMetaModel != null)
{
_myMetaModel.CurrentModelChanged -= MyMetaModelOnCurrentModelChanged;
}
_myMetaModel = value;
// Register new meta-model.
if (_myMetaModel != null)
{
_myMetaModel.CurrentModelChanged += MyMetaModelOnCurrentModelChanged;
}
// Update stuffs which depends on MyMetaModel
UpdateMyModel();
}
}
private void MyMetaModelOnCurrentModelChanged(object sender, EventArgs eventArgs)
{
UpdateMyModel();
}
private void UpdateMyModel()
{
// Yes, the 'MyMetaModel' properties can be changed at any moment by non-UI threads.
var myMetaModel = MyMetaModel;
MyModel = (myMetaModel == null) ? null : myMetaModel.CurrentModel;
}
[CanBeNull]
private MyModel MyModel
{
get { return _myModel; }
set
{
// If nothing new just leave.
if (Equals(_myModel, value)) return;
// Unregister previous model.
if (_myModel != null)
{
_myModel.PropertyChanged -= MyModelOnPropertyChanged;
}
_myModel = value;
// Yep I have child user control who show stuffs depending of 'MyModel'.
childUserControl.MyModel = value;
// Register new model.
if (_myModel != null)
{
_myModel.PropertyChanged += MyModelOnPropertyChanged;
}
// Update UI stuffs which depends on MyModel
UpdateLabelA();
UpdateLabelB();
}
}
private void MyModelOnPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
{
switch (eventArgs.PropertyName)
{
case null: // I forget those two often
case "":
UpdateLabelA();
UpdateLabelB();
break;
case "PropertyA":
UpdateLabelA();
break;
case "PropertyB":
UpdateLabelB();
break;
}
}
private void UpdateLabelA()
{
// Yes, the model can be accessed by non-UI threads.
if (InvokeRequired)
{
Invoke((MethodInvoker) UpdateLabelA);
return;
}
// Take a local copy.
// Yes, the 'MyModel' properties can be changed by non-UI threads.
var myModel = MyModel;
if (myModel == null) return;
// Lets apply the so special formating.
labelA.Text = String.Format("A is: {0}", myModel.PropertyA);
}
private void UpdateLabelB()
{
if (InvokeRequired)
{
Invoke((MethodInvoker) UpdateLabelB);
return;
}
var myModel = MyModel;
if (myModel == null) return;
labelB.Text = String.Format("B is: {0}", myModel.PropertyB);
}
}
And that is a lot of code !!
I will take any advices to enhance this.
I have a problem where I can't find the bug. The Code is:
int b = cusIdChange.Count - 1;
for (int j = 0; j < cusIdChange.Count; j++)
{
col_1Store[j] = Convert.ToDouble(col_1Store[j]) * Convert.ToDouble(multcol_1_Stor.Text);
col_2Store[j] = Convert.ToDouble(col_2Store[j]) * Convert.ToDouble(multcol_2_Stor.Text);
col_1StoreAsString.Add(Convert.ToString(col_1Store[j]));
col_2StoreAsString.Add(Convert.ToString(col_2Store[j]));
if(col_1StoreAsString[j].Contains(","))
{
convertToStringCol1 = col1_StoreAsString[j].Replace(",",".");
}
else
{
convertToStringCol1 = col1_StoreAsString[j];
}
//same if-else Statement here for Col2
DataTable datTableMult = new DataTable();
sqlCmd = new SqlCommand("UPDATE [" + form1.tableNameVal.Text + "] SET ["+form1.getCol_1Name()+"]= convert(varchar(10)," + convertToStringCol1 + ") WHERE " + form1.cusIdBox.Text + cusIdChange[b] +
" AND (" + form1.prodIdBox.Text + prodIdChange[b] + ")", connection);
//same SQL Statement here for Col2
sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection);
sqlDatAdapter.Fill(datTableMult);
form1.setDataGrid3 = datTableMult;
b--;
}
It doesn't want to write the values in my database. Absolutely nothing happens. Both columns have the data type float
, so I convert them to double
in C#.
I have another piece of code thats nearly identical to this one. The difference there is just that I overwrite every single value in the column with a certain entered value and not by a multiplied value like it is in this case. When I use the above code for integers or something else it works fine. I don't know what's wrong with this code. Has to be something with the conversion. When I debug the code, everything looks fine, even the SQL Update
Statement
I'm thinking of doing a project involving sending data generated in a WP8 app (for instance, gyroscope orientation or current geolocation) to a desktop application on a PC over LAN and I'm doing a research on the ways of implementing that. Can you guys give me some tips, directions and/or links to docs (I might've not seen some of them yet) on the subject? Are there any frameworks/libraries for that kind of communication?
Im trying some different alternatives for onscreen keyboard for our desktop application that is being run on a windows 8 tablet without keyboard. So far Tabtip.exe have been working best but im open to other solutions.
The problem i have is when the user clicks on a textbox in the application and i show the onscreen keyboard, the keyboard hides the textbox. How do fix this in a good way? Is it something that windows can handle automatically? Some applications like outlook and word gets a "splitscreen" with a scroll bar in the upper part where the applications is and the keyboard in the lower part. I want a solution like that to. How do they do it?
One solution could be to always move my window up a set amount of pixels that is the same as the keyboard height. But i don't want to move the application if the keyboard doesn't cover the textbox. But how do i determine how high the keyboard is? is it always the same height? How do i detect where the window is?
Any other solutions?
I'm trying to send files by API Google Drive, though, I can not find any documentation on how to perform C # Uploading files using the Authentication Service Account.
I downloaded the Daimto library, however, he uploads using the DriveService class, when we use the authentication ClientId and ClientSecret. But using authentication for account service he returns to PlusService class, and found no way to upload files this way.
Can someone help me? Best regards
Using Authentication Service Account
public PlusService GoogleAuthenticationServiceAccount()
{
String serviceAccountEmail = "106842951064-6s4s95s9u62760louquqo9gu70ia3ev2@developer.gserviceaccount.com";
//var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { PlusService.Scope.PlusMe }
}.FromCertificate(certificate));
// Create the service.
var service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Plus API Sample",
});
return service;
}
Using Authentication ClientId and ClientSecret
public DriveService GoogleAuthentication(string userClientId, string userSecret)
{
//Scopes for use with the Google Drive API
string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = userClientId, ClientSecret = userSecret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GoogleDrive.Auth.Store")).Result;
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample"
});
return service;
}
Daimto class method that makes the file upload to google drive DaimtoGoogleDriveHelper.uploadFile(_service, fileName, item.NomeArquivo, directoryId);
As you can see, the Daimto library, has a method to upload, however, uses the _service parameter, which is the DriveService type, which is what is returned by GoogleAuthentication method. But the GoogleAuthenticationServiceAccount method returns a PlusService type and is incompatible with the DriveService type.
i am beginner for win-forms and i was searching on Google last 2 days . i want that type of ribbon in windows form application file,computer,view etc.
I am using VS 2005 C#, working on an unfinished WinForm.
I have parsed an XML to a treeview listing but I'm encountering some problems. I wanna know if there's a way to hide/filter/remove a certain node containing a "_this_text" in its name without having to depend on a textbox.
This is what I have for the program (kudos to those who helped me develop this):
#region "***** XML Parsing *****"
private void Form1_Load_1(object sender, EventArgs e)
{
// Initialize the controls and the form.
//label1.Text = "File Path";
textBox2.Text = Application.StartupPath + "\\Continental.vsysvar";
//button6.Text = "XML";
//this.Text = "Software Validation";
}
private TreeNode selectedNode = null;
private void button6_Click(object sender, EventArgs e)
{
try
{
// SECTION 1. Create a DOM Document and load the XML data into it.
XmlDocument dom = new XmlDocument();
dom.Load(textBox2.Text);
// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();
/*treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = treeView1.Nodes[0];*/
foreach (XmlNode node in dom.DocumentElement.ChildNodes)
{
if (node.Name == "namespace" && node.ChildNodes.Count == 0 && string.IsNullOrEmpty(GetAttributeText(node, "name")))
continue;
AddNode(treeView1.Nodes, node);
}
treeView1.ExpandAll();
}
/* catch (XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}*/
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void LoadTreeFromXmlDocument(XmlDocument dom)
{
try
{
// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();
// SECTION 3. Populate the TreeView with the DOM nodes.
foreach (XmlNode node in dom.DocumentElement.ChildNodes)
{
if (node.Name == "namespace" && node.ChildNodes.Count == 0 && string.IsNullOrEmpty(GetAttributeText(node, "name")))
continue;
AddNode(treeView1.Nodes, node);
}
treeView1.ExpandAll();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
static string GetAttributeText(XmlNode inXmlNode, string name)
{
XmlAttribute attr = (inXmlNode.Attributes == null ? null : inXmlNode.Attributes[name]);
return attr == null ? null : attr.Value;
}
private void AddNode(TreeNodeCollection nodes, XmlNode inXmlNode)
{
if (inXmlNode.HasChildNodes)
{
string text = GetAttributeText(inXmlNode, "name");
if (string.IsNullOrEmpty(text))
text = inXmlNode.Name;
TreeNode newNode = nodes.Add(text);
XmlNodeList nodeList = inXmlNode.ChildNodes;
for (int i = 0; i <= nodeList.Count - 1; i++)
{
XmlNode xNode = inXmlNode.ChildNodes[i];
AddNode(newNode.Nodes, xNode);
}
}
else
{
// If the node has an attribute "name", use that. Otherwise display the entire text of the node.
string text = GetAttributeText(inXmlNode, "name");
if (string.IsNullOrEmpty(text))
text = (inXmlNode.OuterXml).Trim();
TreeNode newNode = nodes.Add(text);
}
}
#endregion
And here's an excerpt of the XMl file since it's quite long:
<?xml version="1.0" encoding="utf-8"?>
<systemvariables version="4">
<namespace name="" comment="">
<namespace name="_01_Test_Preparation" comment="">
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_02_Shipping_Status_Check" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_02_Shipping_Status_Check_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_01_Get_Dem_ID" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_01_Get_Dem_ID_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_04_ECU_Version_Check_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_03_Test_Run_Init" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_04_ECU_Version_Check" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_05_DEM_Reader" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_03_Test_Run_Init_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
<variable anlyzLocal="2" readOnly="false" valueSequence="false" unit="" name="_01_05_DEM_Reader_start" comment="" bitcount="32" isSigned="true" encoding="65001" type="int" startValue="0" minValue="0" minValuePhys="0" maxValue="4" maxValuePhys="4" />
</namespace>
What I really want to accomplish is to hide or filter the nodes containing this text "_start" found in their name. So all nodes containing "_this_start" in their name would be hidden from the user. I've read that it is not technically possible to enable or disable visibility but instead gray out the text and whatnot.
Thank you in advance.