Search Results

Search found 923 results on 37 pages for 'messagebox'.

Page 17/37 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • How to make a VB exception handling for no value in a Textbox

    - by Twocold
    I want to catch an exception when user enter no value in a Textbox and try to process further by press a button, I know I can use "If else" statement to make it. but in terms of "Try and Catch" block, I dont know how. Here is the code sample. Dim NameString As String Try NameString = OperatorNameTextBox.Text Catch ex As ArgumentException MessageBox.Show("Enter a String Value") End Try

    Read the article

  • why winform using external dll(VC) and ocx(VC) control can only import one?

    - by jack
    we have a .net framework application with a vc dll and a vc ocx, and now if we only import one dll ,it is ok, but when we import both, it will pop a messagebox saying: Debug Assertion Failed! and i studied the child module of our application that import the vc dll, i found after the framework import vc ocx and initialize , then the function LoadLibrary in our module importing the vc dll would return 0, that means memory limited or call improperly, i use getlasterror() the error code is 1114. so it is very frustrated ,hope someone can help me.

    Read the article

  • C++ Edit Box Text Change

    - by user1218395
    Is their any cases in C++ Like these case WM_COMMAND: switch(LOWORD(wParam)) That happen when you change the text of a edit Box, I need to call a function when i change in edit box and store the value of the edit box into a Integer. case EditCD: //ID of your edit { if (HIWORD(wParam) == EN_CHANGE) MessageBox(hwnd, "Text!", "Test!", MB_OK); return TRUE; } Doesnt work did i do it wrong?

    Read the article

  • Check Directories in C# using Linq

    - by pm_2
    Can someone tell me what I'm doing wrong with the following Linq query? I'm trying to find the directory with the highest aphanumerical value. DirectoryInfo[] diList = currentDirectory.GetDirectories(); var dirs = from eachDir in diList orderby eachDir.FullName descending select eachDir; MessageBox.Show(dirs[0].FullName);

    Read the article

  • Alert box not being called upon button click

    - by user279521
    I have a fairly simple code, a button click event, with the first line being a message box. When the button is clicked, the messagebox is not called. protected void btnSubmitToCRM_Click(object sender, EventArgs e) { ClientScript.RegisterStartupScript(GetType(), "alert", "alert('btnSubmitToCRM_Click - 1');", true); if (!ValidateCoreValue()) { ClientScript.RegisterStartupScript(GetType(), "alert", "alert('btnSubmitToCRM_Click - 1 - False');", true); return; } } Any ideas?

    Read the article

  • dialogresult does not work or partially work for some reason

    - by ikel
    I made a form to be a dialog and the form only has one textbox, one OK button and one Cancel button. somehow, when the following does not work unless i change rnmForm.DialogResult!=DialogResult.OK), why is that???? frmRename rnmForm = new frmRename(); rnmForm.ShowDialog(new Form()); if (rnmForm.DialogResult==DialogResult.OK) { MessageBox.Show("test"); }

    Read the article

  • Applications: How to create a custom dialog box for Windows Mobile 6 (native)

    - by TechTwaddle
    Ashraf, on the MSDN forum, asks, “Is there a way to make a default choice for the messagebox that happens after a period of time if the user doesn't choose (Clicked ) Yes or No buttons.” To elaborate, the requirement is to show a message box to the user with certain options to select, and if the user does not respond within a predefined time limit (say 8 seconds) then the message box must dismiss itself and select a default option. Now such a functionality is not available with the MessageBox() api, you will have to write your own custom dialog box. Surely, creating a dialog box is quite a simple task using the DialogBox() api, and we have been creating full screen dialog boxes all the while. So how will this custom message box be any different? It’s not much different from a regular dialog box except for a few changes in its properties. First, it has a title bar but no buttons on the title bar (no ‘x’ or ‘ok’ button on the title bar), it doesn’t occupy full screen and it contains the controls that you put into it, thus justifying the title ‘custom’. So in this post we create a custom dialog box with two buttons, ‘Black’ and ‘White’. The user is given 8 seconds to select one of those colours, if the user doesn’t make a selection in 8 seconds, the default option ‘Black’ is selected. Before going into the implementation here is a video of how the dialog box works; Custom dialog box To start off, add a new dialog resource into your application, size it appropriately and add whatever controls you need to the dialog. In my case, I added two static text labels and two buttons, as below; Now we need to write up the window procedure for this dialog, here is the complete function; BOOL CALLBACK CustomDialogProc(HWND hDlg, UINT uMessage, WPARAM wParam, LPARAM lParam) {     int wmID, wmEvent;     PAINTSTRUCT ps;     HDC hdc;     static int timeCount = 0;     switch(uMessage)     {         case WM_INITDIALOG:             {                 SHINITDLGINFO shidi;                 memset(&shidi, 0, sizeof(shidi));                 shidi.dwMask = SHIDIM_FLAGS;                 //shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN | SHIDIF_EMPTYMENU;                 shidi.dwFlags = SHIDIF_SIPDOWN | SHIDIF_EMPTYMENU;                 shidi.hDlg = hDlg;                 SHInitDialog(&shidi);                 SHDoneButton(hDlg, SHDB_HIDE);                 timeCount = 0;                 SetWindowText(GetDlgItem(hDlg, IDC_STATIC_TIME_REMAINING), L"Time remaining: 8 second(s)");                 SetTimer(hDlg, MY_TIMER, 1000, NULL);             }             return TRUE;         case WM_COMMAND:             {                 wmID = LOWORD(wParam);                 wmEvent = HIWORD(wParam);                 switch(wmID)                 {                     case IDC_BUTTON_BLACK:                         KillTimer(hDlg, MY_TIMER);                         EndDialog(hDlg, IDC_BUTTON_BLACK);                         break;                     case IDC_BUTTON_WHITE:                         KillTimer(hDlg, MY_TIMER);                         EndDialog(hDlg, IDC_BUTTON_WHITE);                         break;                 }             }             break;         case WM_TIMER:             {                 if (wParam == MY_TIMER)                 {                     WCHAR wszText[128];                     memset(&wszText, 0, sizeof(wszText));                     timeCount++;                     //8 seconds are over, dismiss the dialog, select def value                     if (timeCount >= 8)                     {                         KillTimer(hDlg, MY_TIMER);                         EndDialog(hDlg, IDC_BUTTON_BLACK_DEF);                     }                     wsprintf(wszText, L"Time remaining: %d second(s)", 8-timeCount);                     SetWindowText(GetDlgItem(hDlg, IDC_STATIC_TIME_REMAINING), wszText);                     UpdateWindow(GetDlgItem(hDlg, IDC_STATIC_TIME_REMAINING));                 }             }             break;         case WM_PAINT:             {                 hdc = BeginPaint(hDlg, &ps);                 EndPaint(hDlg, &ps);             }             break;     }     return FALSE; } The MSDN documentation mentions that you need to specify the flag WS_NONAVDONEBUTTON, but I got an error saying that the value could not be found, so we can ignore this for now. Next up, while calling SHInitDialog() for your custom dialog, make sure that you don’t specify SHDIF_DONEBUTTON in the dwFlags member of the SHINITDIALOG structure, this member makes the ‘ok’ button appear on the dialog title bar. Finally, we need to call SHDoneButton() with SHDB_HIDE flag to, well, hide the Done button. The ‘Done’ button is the same as the ‘ok’ button, so this step might seem redundant, and the dialog works fine without calling SHDoneButton() too, but it’s better to stick with the documentation (; So you can see that we have followed all these steps above, under WM_INITDIALOG. We also setup a few things like a variable to keep track of the time, and setting off a one second timer. Every time the timer fires, we receive a WM_TIMER message. We then update the static label displaying the amount of time left to the user. If 8 seconds go by without the user selecting any option, we kill the timer and end the dialog with IDC_BUTTON_BLACK_DEF. This is just a #define’d integer value, make sure it’s unique. You’ll see why this is important. If the user makes a selection, either Black or White, we kill the timer and end the dialog with corresponding selection the user made, that is, either IDC_BUTTON_BLACK or IDC_BUTTON_WHITE. Ok, so now our custom dialog is ready to be used. I invoke the custom dialog from a menu entry in the main windows as below, case IDM_MENU_CUSTOMDLG:     {         int ret = DialogBox(g_hInst, MAKEINTRESOURCE(IDD_CUSTOM_DIALOG), hWnd, CustomDialogProc);         switch(ret)         {             case IDC_BUTTON_BLACK_DEF:                 SetWindowText(g_hStaticSelection, L"You Selected: Black (default)");                 break;             case IDC_BUTTON_BLACK:                 SetWindowText(g_hStaticSelection, L"You Selected: Black");                 break;             case IDC_BUTTON_WHITE:                 SetWindowText(g_hStaticSelection, L"You Selected: White");                 break;         }         UpdateWindow(g_hStaticSelection);     }     break; So you see why ending the dialog with the corresponding value was important, that’s what the DialogBox() api returns with. And in the main window I update a static text label to show which option was selected. I cranked this out in about an hour, and unfortunately don’t have time for a managed C# version. That will have to be another post, if I manage to get it working that is (;

    Read the article

  • Silverlight 4 Twitter Client &ndash; Part 3

    - by Max
    Finally Silverlight 4 RC is released and also that Windows 7 Phone Series will rely heavily on Silverlight platform for apps platform. its a really good news for Silverlight developers and designers. More information on this here. You can use SL 4 RC with VS 2010. SL 4 RC does not come with VS 2010, you need to download it separately and install it. So for the next part, be ready with VS 2010 and SL4 RC, we will start using them and not With this momentum, let us go to the next part of our twitter client tutorial. This tutorial will cover setting your status in Twitter and also retrieving your 1) As everything in Silverlight is asynchronous, we need to have some visual representation showing that something is going on in the background. So what I did was to create a progress bar with indeterminate animation. The XAML is here below. <ProgressBar Maximum="100" Width="300" Height="50" Margin="20" Visibility="Collapsed" IsIndeterminate="True" Name="progressBar1" VerticalAlignment="Center" HorizontalAlignment="Center" /> 2) I will be toggling this progress bar to show the background work. So I thought of writing this small method, which I use to toggle the visibility of this progress bar. Just pass a bool to this method and this will toggle it based on its current visibility status. public void toggleProgressBar(bool Option){ if (Option) { if (progressBar1.Visibility == System.Windows.Visibility.Collapsed) progressBar1.Visibility = System.Windows.Visibility.Visible; } else { if (progressBar1.Visibility == System.Windows.Visibility.Visible) progressBar1.Visibility = System.Windows.Visibility.Collapsed; }} 3) Now let us create a grid to hold a textbox and a update button. The XAML will look like something below <Grid HorizontalAlignment="Center"> <Grid.RowDefinitions> <RowDefinition Height="50"></RowDefinition> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="400"></ColumnDefinition> <ColumnDefinition Width="200"></ColumnDefinition> </Grid.ColumnDefinitions> <TextBox Name="TwitterStatus" Width="380" Height="50"></TextBox> <Button Name="UpdateStatus" Content="Update" Grid.Row="1" Grid.Column="2" Width="200" Height="50" Click="UpdateStatus_Click"></Button></Grid> 4) The click handler for this update button will be again using the Web Client to post values. Posting values using Web Client. The code is: private void UpdateStatus_Click(object sender, RoutedEventArgs e){ toggleProgressBar(true); string statusupdate = "status=" + TwitterStatus.Text; WebRequest.RegisterPrefix("https://", System.Net.Browser.WebRequestCreator.ClientHttp);  WebClient myService = new WebClient(); myService.AllowReadStreamBuffering = true; myService.UseDefaultCredentials = false; myService.Credentials = new NetworkCredential(GlobalVariable.getUserName(), GlobalVariable.getPassword());  myService.UploadStringCompleted += new UploadStringCompletedEventHandler(myService_UploadStringCompleted); myService.UploadStringAsync(new Uri("https://twitter.com/statuses/update.xml"), statusupdate);  this.Dispatcher.BeginInvoke(() => ClearTextBoxValue());} 5) In the above code, we have a event handler which will be fired on this request is completed – !! Remember SL is Asynch !! So in the myService_UploadStringCompleted, we will just toggle the progress bar and change some status text to say that its done. The code for this will be StatusMessage is just another textblock conveniently positioned in the page.  void myService_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e){ if (e.Error != null) { StatusMessage.Text = "Status Update Failed: " + e.Error.Message.ToString(); } else { toggleProgressBar(false); TwitterCredentialsSubmit(); }} 6) Now let us look at fetching the friends updates of the logged in user and displaying it in a datagrid. So just define a data grid and set its autogenerate columns as true. 7) Let us first create a data structure for use with fetching the friends timeline. The code is something like below: namespace MaxTwitter.Classes{ public class Status { public Status() {} public string ID { get; set; } public string Text { get; set; } public string Source { get; set; } public string UserID { get; set; } public string UserName { get; set; } }} You can add as many fields as you want, for the list of fields, have a look at here. It will ask for your Twitter username and password, just provide them and this will display the xml file. Go through them pick and choose your desired fields and include in your Data Structure. 8) Now the web client request for this is similar to the one we saw in step 4. Just change the uri in the last but one step to https://twitter.com/statuses/friends_timeline.xml Be sure to change the event handler to something else and within that we will use XLINQ to fetch the required details for us. Now let us how this event handler fetches details. public void parseXML(string text){ XDocument xdoc; if(text.Length> 0) xdoc = XDocument.Parse(text); else xdoc = XDocument.Parse(@"I USED MY OWN LOCAL COPY OF XML FILE HERE FOR OFFLINE TESTING"); statusList = new List<Status>(); statusList = (from status in xdoc.Descendants("status") select new Status { ID = status.Element("id").Value, Text = status.Element("text").Value, Source = status.Element("source").Value, UserID = status.Element("user").Element("id").Value, UserName = status.Element("user").Element("screen_name").Value, }).ToList(); //MessageBox.Show(text); //this.Dispatcher.BeginInvoke(() => CallDatabindMethod(StatusCollection)); //MessageBox.Show(statusList.Count.ToString()); DataGridStatus.ItemsSource = statusList; StatusMessage.Text = "Datagrid refreshed."; toggleProgressBar(false);} in the event handler, we call this method with e.Result.ToString() Parsing XML files using LINQ is super cool, I love it.   I am stopping it here for  this post. Will post the completed files in next post, as I’ve worked on a few more features in this page and don’t want to confuse you. See you soon in my next post where will play with Twitter lists. Have a nice day! Technorati Tags: Silverlight,LINQ,XLINQ,Twitter API,Twitter,Network Credentials

    Read the article

  • Configure Windows XP Embedded to automatically dismiss unexpected MessageBoxes

    - by Pokot0
    I have the need to configure a Windows XP Embedded system in order to dismiss modal MessageBoxes with a default reply. I am aware of the EnableDefaultReply feature but I need to be more selective on which MessageBoxes to dismiss or select the default reply on some criteria (example: name of the window). My biggest problem right now is that: If do not enable the EnableDefaultReply feature: some background services pop up dialogboxes which are never dismissed and block the application If I enable the EnableDefaultReply feature: I am no longer able to logon to the system if another user is logged in (a MessageBox popups asking if you want to steal the logon and the default answer is NO). Do you have any experience you can share with this problem?

    Read the article

  • cannot access my own computer through My Network Places

    - by vgv8
    My home Windows XP Pro SP3 machine is DHCP client receiving configurations from ISP. Trying to access in WindowsExplorer -My Network Places - Microsoft Windows Network shows Workgroup with a delay of 3 min and then popups messagebox: Microsoft Windows Network Workgroup is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions.The list of servers for this workgroup is not currently available OK I am logged-in as local machine Administrator. The internet is accessible (I am writing this post through it) The Firewall is disabled The "Computer Bowser" and all networking services, I could find, are running Control Panel -- Network Connections -- Properties (of connection) --- Internet Protocol (TCP/IP), btn Properties --- --- tab General, btn "Advanced..." -- tab WINS-- rbtn "Enable NetBIOS over TCP/IP" checked Why cannot I access my own PC (and shares on it) through My Network Places What is the possible problem? How to daignose the problem?

    Read the article

  • cannot access my own computer through My Network Places

    - by WebMAOhist
    My home Windows XP Pro SP3 machine is DHCP client receiving configurations from ISP. Trying to access in WindowsExplorer -My Network Places - Microsoft Windows Network shows Workgroup with a delay of 3 min and then popups messagebox: Microsoft Windows Network Workgroup is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions.The list of servers for this workgroup is not currently available OK I am logged-in as local machine Administrator. The internet is accessible (I am writing this post through it) The Firewall is disabled The "Computer Bowser" and all networking services, I could find, are running Control Panel -- Network Connections -- Properties (of connection) --- Internet Protocol (TCP/IP), btn Properties --- --- tab General, btn "Advanced..." -- tab WINS-- rbtn "Enable NetBIOS over TCP/IP" checked Why cannot I access my own PC (and shares on it) through My Network Places What is the possible problem? How to daignose the problem?

    Read the article

  • How to print all users from windows-group to a textfile?

    - by Tim
    Hello, i'm trying to print all users of a group "Students" to a Textfile "Students.txt". I'm not in a domain, so this does not work: net group "Students" >> students.txt because i get following: This command can be used only on a Windows Domain Controller. Thank you in advance If anybody is interested in a VB.Net solution, i've programmed a Winform solution with a multiline Textbox to copy/paste the members (anyway, thanks for your help): Imports System.DirectoryServices 'first add a refernce to it from .Net Tab' .... Private Sub PrintGroupMember_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim students As List(Of DirectoryEntry) = MembersOfGroup("Students") For Each user As DirectoryEntry In students Me.TextBox1.Text &= user.Name & vbCrLf Next End Sub Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry) Dim members As New List(Of DirectoryEntry) Try Using search As New DirectoryEntry("WinNT://./" & GroupName & ",group") For Each member As Object In DirectCast(search.Invoke("Members"), IEnumerable) Dim memberEntry As New DirectoryEntry(member) members.Add(memberEntry) Next End Using Catch ex As Exception MessageBox.Show(ex.ToString) End Try Return members End Function

    Read the article

  • MVVM: Binding radio buttons to a view model?

    - by David Veeneman
    I have been trying to bind a group of radio buttons to a view model using the IsChecked button. After reviewing other posts, it appears that the IsChecked property simply doesn't work. I have put together a short demo that reproduces the problem, which I have included below. Here is my question: Is there a straightforward and reliable way to bind radio buttons using MVVM? Thanks. Additional information: The IsChecked property doesn't work for two reasons: When a button is selected, the IsChecked properties of other buttons in the group don't get set to false. When a button is selected, its own IsChecked property does not get set after the first time the button is selected. I am guessing that the binding is getting trashed by WPF on the first click. Demo project: Here is the code and markup for a simple demo that reproduces the problem. Create a WPF project and replace the markup in Window1.xaml with the following: <Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300" Loaded="Window_Loaded"> <StackPanel> <RadioButton Content="Button A" IsChecked="{Binding Path=ButtonAIsChecked, Mode=TwoWay}" /> <RadioButton Content="Button B" IsChecked="{Binding Path=ButtonBIsChecked, Mode=TwoWay}" /> </StackPanel> </Window> Replace the code in Window1.xaml.cs with the following code (a hack), which sets the view model: using System.Windows; namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { this.DataContext = new Window1ViewModel(); } } } Now add the following code to the project as Window1ViewModel.cs: using System.Windows; namespace WpfApplication1 { public class Window1ViewModel { private bool p_ButtonAIsChecked; /// <summary> /// Summary /// </summary> public bool ButtonAIsChecked { get { return p_ButtonAIsChecked; } set { p_ButtonAIsChecked = value; MessageBox.Show(string.Format("Button A is checked: {0}", value)); } } private bool p_ButtonBIsChecked; /// <summary> /// Summary /// </summary> public bool ButtonBIsChecked { get { return p_ButtonBIsChecked; } set { p_ButtonBIsChecked = value; MessageBox.Show(string.Format("Button B is checked: {0}", value)); } } } } To reproduce the problem, run the app and click Button A. A message box will appear, saying that Button A's IsChecked property has been set to true. Now select Button B. Another message box will appear, saying that Button B's IsChecked property has been set to true, but there is no message box indicating that Button A's IsChecked property has been set to false--the property hasn't been changed. Now click Button A again. The button will be selected in the window, but no message box will appear--the IsChecked property has not been changed. Finally, click on Button B again--same result. The IsChecked property is not updated at all for either button after the button is first clicked.

    Read the article

  • c# opennetCF background worker - e.result gives a ObjectDisposedException

    - by ikky
    Hi! I'm new working with background worker in C#. Here is a class, and under it, you will find the instansiation of it, and under there i will define my problem for you: I have the class Drawing: class Drawing { BackgroundWorker bgWorker; ProgressBar progressBar; Panel panelHolder; public Drawing(ref ProgressBar pgbar, ref Panel panelBig) // Progressbar and panelBig as reference { this.panelHolder = panelBig; this.progressBar = pgbar; bgWorker = new BackgroundWorker(); bgWorker.WorkerReportsProgress = true; bgWorker.WorkerSupportsCancellation = true; bgWorker.DoWork += new OpenNETCF.ComponentModel.DoWorkEventHandler(this.bgWorker_DoWork); bgWorker.RunWorkerCompleted += new OpenNETCF.ComponentModel.RunWorkerCompletedEventHandler(this.bgWorker_RunWorkerCompleted); bgWorker.ProgressChanged += new OpenNETCF.ComponentModel.ProgressChangedEventHandler(this.bgWorker_ProgressChanged); } public void createDrawing() { bgWorker.RunWorkerAsync(); } private void bgWorker_DoWork(object sender, DoWorkEventArgs e) { Panel panelContainer = new Panel(); // Adding panels to the panelContainer for(i=0; i<100; i++) { Panel panelSubpanel = new Panel(); // Setting size, color, name etc.... panelContainer.Controls.Add(panelSubpanel); // Adding the subpanel to the panelContainer //Report the progress bgWorker.ReportProgress(0, i); // Reporting number of panels loaded } e.Result = imagePanel; // Send the result(a panel with lots of subpanels) as an argument } private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.progressBar.Value = (int)e.UserState; this.progressBar.Update(); } private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error == null) { this.panelHolder = (Panel)e.Result; } else { MessageBox.Show("An error occured, please try again"); } } } Instansiating an object of this class: public partial class Draw: Form { public Draw() { ProgressBar progressBarLoading = new ProgressBar(); // Set lots of properties on progressBarLoading Panel panelBigPanelContainer = new Panel(); Drawing drawer = new Drawing(ref progressBarLoading, ref panelBigPanelContainer); drawer.createDrawing(); // this makes the object start a new thread, loading all the panels into a panel container, while also sending the progress to this progressbar. } } Here is my problem: In the private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) i don't get the e.Result as it should be. When i debug and look at the e.Result, the panel's properties have this exception message: '((System.Windows.Forms.Control)(e.Result)).ClientSize' threw an exception of type 'System.ObjectDisposedException' So the object gets disposed, but "why" is my question, and how can i fix this? I hope someone will answer me, this is making me crazy. Another question i have: Is it allowed to use "ref" with arguments? is it bad programming? Thanks in advance. I have also written how i understand the Background worker below here: This is what i think is the "rules" for background workers: bgWorker.RunWorkerAsync(); => starts a new thread. bgWorker_DoWork cannot reach the main thread without delegates - private void bgWorker_DoWork(object sender, DoWorkEventArgs e) { // The work happens here, this is a thread that is not reachable by the main thread e.Result => This is an argument which can be reached by bgWorker_RunWorkerCompleted() bgWorker.ReportProgress(progressVar); => Reports the progress to the bgWorker_ProgressChanged() } - private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { // I get the progress here, and can do stuff to the main thread from here (e.g update a control) this.ProgressBar.Value = e.ProgressPercentage; } - private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // This is where the thread is completed. // Here i can get e.Result from the bgWorker thread // From here i can reach controls in my main thread, and use e.Result in my main thread if (e.Error == null) { this.panelTileHolder = (Panel)e.Result; } else { MessageBox.Show("There was an error"); } }

    Read the article

  • TwoWay Binding With ItemsControl

    - by Andrew
    I'm trying to write a user control that has an ItemsControl, the ItemsTemplate of which contains a TextBox that will allow for TwoWay binding. However, I must be making a mistake somewhere in my code, because the binding only appears to work as if Mode=OneWay. This is a pretty simplified excerpt from my project, but it still contains the problem: <UserControl x:Class="ItemsControlTest.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"> <Grid> <StackPanel> <ItemsControl ItemsSource="{Binding Path=.}" x:Name="myItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Mode=TwoWay, UpdateSourceTrigger=LostFocus, Path=.}" /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> <Button Click="Button_Click" Content="Click Here To Change Focus From ItemsControl" /> </StackPanel> </Grid> </UserControl> Here's the code behind for the above control: using System; using System.Windows; using System.Windows.Controls; using System.Collections.ObjectModel; namespace ItemsControlTest { /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class UserControl1 : UserControl { public ObservableCollection<string> MyCollection { get { return (ObservableCollection<string>)GetValue(MyCollectionProperty); } set { SetValue(MyCollectionProperty, value); } } // Using a DependencyProperty as the backing store for MyCollection. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyCollectionProperty = DependencyProperty.Register("MyCollection", typeof(ObservableCollection<string>), typeof(UserControl1), new UIPropertyMetadata(new ObservableCollection<string>())); public UserControl1() { for (int i = 0; i < 6; i++) MyCollection.Add("String " + i.ToString()); InitializeComponent(); myItemsControl.DataContext = this.MyCollection; } private void Button_Click(object sender, RoutedEventArgs e) { // Insert a string after the third element of MyCollection MyCollection.Insert(3, "Inserted Item"); // Display contents of MyCollection in a MessageBox string str = ""; foreach (string s in MyCollection) str += s + Environment.NewLine; MessageBox.Show(str); } } } And finally, here's the xaml for the main window: <Window x:Class="ItemsControlTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:ItemsControlTest" Title="Window1" Height="300" Width="300"> <Grid> <src:UserControl1 /> </Grid> </Window> Well, that's everything. I'm not sure why editing the TextBox.Text properties in the window does not seem to update the source property for the binding in the code behind, namely MyCollection. Clicking on the button pretty much causes the problem to stare me in the face;) Please help me understand where I'm going wrong. Thanx! Andrew

    Read the article

  • WTSVirtualChannelRead Only reads the first letter of the string.

    - by Scott Chamberlain
    I am trying to write a hello world type program for using virtual channels in the windows terminal services client. public partial class Form1 : Form { public Form1() { InitializeComponent(); } IntPtr mHandle = IntPtr.Zero; private void Form1_Load(object sender, EventArgs e) { mHandle = NativeMethods.WTSVirtualChannelOpen(IntPtr.Zero, -1, "TSCRED"); if (mHandle == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } private void button1_Click(object sender, EventArgs e) { uint bufferSize = 1024; StringBuilder buffer = new StringBuilder(); uint bytesRead; NativeMethods.WTSVirtualChannelRead(mHandle, 0, buffer, bufferSize, out bytesRead); if (bytesRead == 0) { MessageBox.Show("Got no Data"); } else { MessageBox.Show("Got data: " + buffer.ToString()); } } protected override void Dispose(bool disposing) { if (mHandle != System.IntPtr.Zero) { NativeMethods.WTSVirtualChannelClose(mHandle); } base.Dispose(disposing); } } internal static class NativeMethods { [DllImport("Wtsapi32.dll")] public static extern IntPtr WTSVirtualChannelOpen(IntPtr server, int sessionId, [MarshalAs(UnmanagedType.LPStr)] string virtualName); //[DllImport("Wtsapi32.dll", SetLastError = true)] //public static extern bool WTSVirtualChannelRead(IntPtr channelHandle, long timeout, // byte[] buffer, int length, ref int bytesReaded); [DllImport("Wtsapi32.dll")] public static extern bool WTSVirtualChannelClose(IntPtr channelHandle); [DllImport("Wtsapi32.dll", EntryPoint = "WTSVirtualChannelRead")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WTSVirtualChannelRead( [In()] System.IntPtr hChannelHandle , uint TimeOut , [Out()] [MarshalAs(UnmanagedType.LPStr)] System.Text.StringBuilder Buffer , uint BufferSize , [Out()] out uint pBytesRead); } I am sending the data from the MSTSC COM object and ActiveX controll. public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { rdp.Server = "schamberlainvm"; rdp.UserName = "TestAcct"; IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx(); secured.ClearTextPassword = "asdf"; rdp.CreateVirtualChannels("TSCRED"); rdp.Connect(); } private void button1_Click(object sender, EventArgs e) { rdp.SendOnVirtualChannel("TSCRED", "Hello World!"); } } //Designer code // // rdp // this.rdp.Enabled = true; this.rdp.Location = new System.Drawing.Point(12, 12); this.rdp.Name = "rdp"; this.rdp.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("rdp.OcxState"))); this.rdp.Size = new System.Drawing.Size(1092, 580); this.rdp.TabIndex = 0; I am getting a execption every time NativeMethods.WTSVirtualChannelRead runs Any help on this would be greatly appreciated. EDIT -- mHandle has a non-zero value when the function runs. updated code to add that check. EDIT2 -- I used the P/Invoke Interop Assistant and generated a new sigiture [DllImport("Wtsapi32.dll", EntryPoint = "WTSVirtualChannelRead")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WTSVirtualChannelRead( [In()] System.IntPtr hChannelHandle , uint TimeOut , [Out()] [MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer , uint BufferSize , [Out()] out uint pBytesRead); it now receives the text string (Yea!) but it only gets the first letter of my test string(Boo!). Any ideas on what is going wrong? EDIT 3 --- After the call that should of read the hello world; BytesRead = 24 Buffer.Length = 1; Buffer.Capacity = 16; Buffer.m_StringValue = "H";

    Read the article

  • Access Violation Exception when trying to perform WTSVirtualChannelRead

    - by Scott Chamberlain
    I am trying to write a hello world type program for using virtual channels in the windows terminal services client. public partial class Form1 : Form { public Form1() { InitializeComponent(); } IntPtr mHandle = IntPtr.Zero; private void Form1_Load(object sender, EventArgs e) { mHandle = NativeMethods.WTSVirtualChannelOpen(IntPtr.Zero, -1, "TSCRED"); } private void button1_Click(object sender, EventArgs e) { int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; NativeMethods.WTSVirtualChannelRead(mHandle, 0, buffer, bufferSize, ref bytesRead); if (bytesRead != 0) { MessageBox.Show("Got no Data"); } else { MessageBox.Show("Got data: " + bytesRead); } } protected override void Dispose(bool disposing) { if (mHandle != System.IntPtr.Zero) { NativeMethods.WTSVirtualChannelClose(mHandle); } base.Dispose(disposing); } } internal static class NativeMethods { [DllImport("Wtsapi32.dll")] public static extern IntPtr WTSVirtualChannelOpen(IntPtr server, int sessionId, [MarshalAs(UnmanagedType.LPStr)] string virtualName); [DllImport("Wtsapi32.dll", SetLastError = true)] public static extern bool WTSVirtualChannelRead(IntPtr channelHandle, long timeout, byte[] buffer, int length, ref int bytesReaded); [DllImport("Wtsapi32.dll")] public static extern bool WTSVirtualChannelClose(IntPtr channelHandle); } On NativeMethods.WTSVirtualChannelRead(mHandle, 0, buffer, bufferSize, ref bytesRead); I get the following error every time. System.AccessViolationException was unhandled by user code Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Source=RemoteForm StackTrace: at RemoteForm.NativeMethods.WTSVirtualChannelRead(IntPtr channelHandle, Int64 timeout, Byte[] buffer, Int32 length, Int32& bytesReaded) at RemoteForm.Form1.button1_Click(Object sender, EventArgs e) in E:\Visual Studio 2010\Projects\RemoteForm\Form1.cs:line 31 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) InnerException: I am sending the data from the MSTSC COM object and ActiveX controll. public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { rdp.Server = "schamberlainvm"; rdp.UserName = "TestAcct"; IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx(); secured.ClearTextPassword = "asdf"; rdp.CreateVirtualChannels("TSCRED"); rdp.Connect(); } private void button1_Click(object sender, EventArgs e) { rdp.SendOnVirtualChannel("TSCRED", "This is a test"); } } //Designer code // // rdp // this.rdp.Enabled = true; this.rdp.Location = new System.Drawing.Point(12, 12); this.rdp.Name = "rdp"; this.rdp.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("rdp.OcxState"))); this.rdp.Size = new System.Drawing.Size(1092, 580); this.rdp.TabIndex = 0; Any help on this would be greatly appreciated.

    Read the article

  • Deserializing Metafile

    - by Kildareflare
    I have an application that works with Enhanced Metafiles. I am able to create them, save them to disk as .emf and load them again no problem. I do this by using the gdi32.dll methods and the DLLImport attribute. However, to enable Version Tolerant Serialization I want to save the metafile in an object along with other data. This essentially means that I need to serialize the metafile data as a byte array and then deserialize it again in order to reconstruct the metafile. The problem I have is that the deserialized data would appear to be corrupted in some way, since the method that I use to reconstruct the Metafile raises a "Parameter not valid exception". At the very least the pixel format and resolutions have changed. Code use is below. [DllImport("gdi32.dll")] public static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer); [DllImport("gdi32.dll")] public static extern IntPtr SetEnhMetaFileBits(uint cbBuffer, byte[] lpBuffer); [DllImport("gdi32.dll")] public static extern bool DeleteEnhMetaFile(IntPtr hemf); The application creates a metafile image and passes it to the method below. private byte[] ConvertMetaFileToByteArray(Image image) { byte[] dataArray = null; Metafile mf = (Metafile)image; IntPtr enhMetafileHandle = mf.GetHenhmetafile(); uint bufferSize = GetEnhMetaFileBits(enhMetafileHandle, 0, null); if (enhMetafileHandle != IntPtr.Zero) { dataArray = new byte[bufferSize]; GetEnhMetaFileBits(enhMetafileHandle, bufferSize, dataArray); } DeleteEnhMetaFile(enhMetafileHandle); return dataArray; } At this point the dataArray is inserted into an object and serialized using a BinaryFormatter. The saved file is then deserialized again using a BinaryFormatter and the dataArray retrieved from the object. The dataArray is then used to reconstruct the original Metafile using the following method. public static Image ConvertByteArrayToMetafile(byte[] data) { Metafile mf = null; try { IntPtr hemf = SetEnhMetaFileBits((uint)data.Length, data); mf = new Metafile(hemf, true); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } return (Image)mf; } The reconstructed metafile is then saved saved to disk as a .emf (Model) at which point it can be accessed by the Presenter for display. private static void SaveFile(Image image, String filepath) { try { byte[] buffer = ConvertMetafileToByteArray(image); File.WriteAllBytes(filepath, buffer); //will overwrite file if it exists } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } The problem is that the save to disk fails. If this same method is used to save the original Metafile before it is serialized everything is OK. So something is happening to the data during serialization/deserializtion. Indeed if I check the Metafile properties in the debugger I can see that the ImageFlags, PropertyID, resolution and pixelformats change. Original Format32bppRgb changes to Format32bppArgb Original Resolution 81 changes to 96 I've trawled though google and SO and this has helped me get this far but Im now stuck. Does any one have enough experience with Metafiles / serialization to help..? EDIT: If I serialize/deserialize the byte array directly (without embedding in another object) I get the same problem.

    Read the article

  • C# Request not timing out

    - by Joel Kennedy
    I have this code which runs in a BackgroundWorker, and should make a POST request to the server and get a response. It works fine when it is supposed to work, but when I try to induce a 404 error it doesn't catch the error reporting system. loginProcess.DoWork += delegate(object s, DoWorkEventArgs args) { // loginProcess BackgroundWorker try { // Try to login, if error, report loginProcess.ReportProgress(10); String method = "POST"; String postdata = "postdata=test"; String url = "http://localhost/dev/login.php"; loginProcess.ReportProgress(15); WebRequest rqst = HttpWebRequest.Create(url); rqst.Timeout = 5000; ((HttpWebRequest)rqst).KeepAlive = true; loginProcess.ReportProgress(20); //rqst.Timeout = this.Timeout; // only needed, if you use HTTP AUTH //CredentialCache creds = new CredentialCache(); //creds.Add(new Uri(url), "Basic", new NetworkCredential(this.Uname, this.Pwd)); //rqst.Credentials = creds; rqst.Method = method; if (!String.IsNullOrEmpty(postdata)) { //rqst.ContentType = "application/xml"; rqst.ContentType = "application/x-www-form-urlencoded"; loginProcess.ReportProgress(30); byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata); loginProcess.ReportProgress(40); rqst.ContentLength = byteData.Length; loginProcess.ReportProgress(50); using (Stream postStream = rqst.GetRequestStream()) { loginProcess.ReportProgress(50); postStream.Write(byteData, 0, byteData.Length); loginProcess.ReportProgress(60); postStream.Close(); loginProcess.ReportProgress(70); rqst.GetResponse().Close(); rqst.GetRequestStream().Close(); } } loginProcess.ReportProgress(90); using (var response1 = rqst.GetResponse()) { using (var responseStream1 = response1.GetResponseStream()) { using (var reader1 = new StreamReader(responseStream1)) { //StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream()); string strRsps = reader1.ReadToEnd(); loginProcess.ReportProgress(95); loginVars = strRsps; //rqst. //reader1.Close(); //rsps.Dispose(); } args.Result = "SUCCESS"; } } } catch(WebException err) { // Catch error and put into err variable if(err.Status == WebExceptionStatus.ProtocolError) { // If something is wrong with protocol LoginReporting.ErrorName = Convert.ToString(((HttpWebResponse)err.Response).StatusCode); LoginReporting.ErrorDescription = Convert.ToString(((HttpWebResponse)err.Response).StatusDescription); LoginReporting.ErrorNotes = "Error when logging in, Server returned: " + Convert.ToString(((HttpWebResponse)err.Response).StatusCode); LoginReporting.ErrorLocation = "LoginRequest.ProtocolError"; args.Result = "ERROR"; //MessageBox.Show(Convert.ToString(((HttpWebResponse)err.Response).StatusCode)); //MessageBox.Show(Convert.ToString(((HttpWebResponse)err.Response).StatusDescription)); } else { args.Result = "ERROR"; } } catch(Exception err) { // Catch unhandled error LoginReporting.ErrorName = Convert.ToString(err); LoginReporting.ErrorDescription = Convert.ToString(err.Message); LoginReporting.ErrorNotes = "Error when logging in, Server returned: " + Convert.ToString(err.Message); LoginReporting.ErrorLocation = "LoginRequest.ProtocolError"; args.Result = "ERROR"; } }; I have put a timeout on the request but it just doesn't work! Is this a bug, or am I doing something wrong here? Thanks

    Read the article

  • how to insert data if it contain apostrophe ?

    - by angel ansari
    Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; namespace tool { public partial class Form1 : Form { StreamReader reader; SqlConnection con; SqlCommand cmd; int count = 0; //int id=0; FileStream fs; string file = null; string file_path = null; SqlCommand sql_del = null; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog file1 = new OpenFileDialog(); file1.ShowDialog(); textBox1.Text = file1.FileName.ToString(); file = Path.GetFileName(textBox1.Text); file_path = textBox1.Text; fs = new FileStream(file_path, FileMode.Open, FileAccess.Read); } private void button2_Click(object sender, EventArgs e) { if (file != null ) { sql_del = new SqlCommand("Delete From credit_debit1", con); sql_del.ExecuteNonQuery(); reader = new StreamReader(file_path); string line_content = null; string[] items = new string[] { }; while ((line_content = reader.ReadLine()) != null) { if (count >=4680) { items = line_content.Split(','); string region = items[0].Trim('"'); string station = items[1].Trim('"'); string ponumber = items[2].Trim('"'); string invoicenumber = items[3].Trim('"'); string invoicetype = items[4].Trim('"'); string filern = items[5].Trim('"'); string client = items[6].Trim('"'); string origin = items[7].Trim('"'); string destination = items[8].Trim('"'); string agingdate = items[9].Trim('"'); string activitydate = items[10].Trim('"'); if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber))) { invoicenumber = "null"; } else { invoicenumber = "'" + invoicenumber + "'"; } if ((destination == "-") || (string.IsNullOrEmpty(destination))) { destination = "null"; } else { destination = "'" + destination + "'"; } string vendornumber = items[11].Trim('"'); string vendorname = items[12].Trim('"'); string vendorsite = items[13].Trim('"'); string vendorref = items[14].Trim('"'); string subaccount = items[15].Trim('"'); string osdaye = items[16].Trim('"'); string osaa = items[17].Trim('"'); string osda = items[18].Trim('"'); string our = items[19].Trim('"'); string squery = "INSERT INTO credit_debit1" + "([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " + "[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " + "[OverUnderRecovery] ) " + "VALUES " + "('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," + "'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," + "'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') "; cmd = new SqlCommand(squery, con); cmd.CommandTimeout = 1500; cmd.ExecuteNonQuery(); } label2.Text = count.ToString(); Application.DoEvents(); count++; } MessageBox.Show("Process completed"); } else { MessageBox.Show("path select"); } } private void button3_Click(object sender, EventArgs e) { this.Close(); } private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;"); con.Open(); } } } vendername field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data

    Read the article

  • how to insert data if it contain apostrop ?

    - by angel ansari
    Actally my task is load csv file into sql server using c# so i have split it by comma my problem is that some field's data contain apostrop and i m firing insert query to load data into sql so its give error my coding like that using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; namespace tool { public partial class Form1 : Form { StreamReader reader; SqlConnection con; SqlCommand cmd; int count = 0; //int id=0; FileStream fs; string file = null; string file_path = null; SqlCommand sql_del = null; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { OpenFileDialog file1 = new OpenFileDialog(); file1.ShowDialog(); textBox1.Text = file1.FileName.ToString(); file = Path.GetFileName(textBox1.Text); file_path = textBox1.Text; fs = new FileStream(file_path, FileMode.Open, FileAccess.Read); } private void button2_Click(object sender, EventArgs e) { if (file != null ) { sql_del = new SqlCommand("Delete From credit_debit1", con); sql_del.ExecuteNonQuery(); reader = new StreamReader(file_path); string line_content = null; string[] items = new string[] { }; while ((line_content = reader.ReadLine()) != null) { if (count >=4680) { items = line_content.Split(','); string region = items[0].Trim('"'); string station = items[1].Trim('"'); string ponumber = items[2].Trim('"'); string invoicenumber = items[3].Trim('"'); string invoicetype = items[4].Trim('"'); string filern = items[5].Trim('"'); string client = items[6].Trim('"'); string origin = items[7].Trim('"'); string destination = items[8].Trim('"'); string agingdate = items[9].Trim('"'); string activitydate = items[10].Trim('"'); if ((invoicenumber == "-") || (string.IsNullOrEmpty(invoicenumber))) { invoicenumber = "null"; } else { invoicenumber = "'" + invoicenumber + "'"; } if ((destination == "-") || (string.IsNullOrEmpty(destination))) { destination = "null"; } else { destination = "'" + destination + "'"; } string vendornumber = items[11].Trim('"'); string vendorname = items[12].Trim('"'); string vendorsite = items[13].Trim('"'); string vendorref = items[14].Trim('"'); string subaccount = items[15].Trim('"'); string osdaye = items[16].Trim('"'); string osaa = items[17].Trim('"'); string osda = items[18].Trim('"'); string our = items[19].Trim('"'); string squery = "INSERT INTO credit_debit1" + "([id],[Region],[Station],[PONumber],[InvoiceNumber],[InvoiceType],[FileRefNumber],[Client],[Origin],[Destination], " + "[AgingDate],[ActivityDate],[VendorNumber],[VendorName],[VendorSite],[VendorRef],[SubAccount],[OSDay],[OSAdvAmt],[OSDisbAmt], " + "[OverUnderRecovery] ) " + "VALUES " + "('" + count + "','" + region + "','" + station + "','" + ponumber + "'," + invoicenumber + ",'" + invoicetype + "','" + filern + "','" + client + "','" + origin + "'," + destination + "," + "'" + (string)agingdate.ToString() + "','" + (string)activitydate.ToString() + "','" + vendornumber + "',' " + vendorname + "',' " + vendorsite + "',' " + vendorref + "'," + "'" + subaccount + "','" + osdaye + "','" + osaa + "','" + osda + "','" + our + "') "; cmd = new SqlCommand(squery, con); cmd.CommandTimeout = 1500; cmd.ExecuteNonQuery(); } label2.Text = count.ToString(); Application.DoEvents(); count++; } MessageBox.Show("Process completed"); } else { MessageBox.Show("path select"); } } private void button3_Click(object sender, EventArgs e) { this.Close(); } private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("Data Source=192.168.50.200;User ID=EGL_TEST;Password=TEST;Initial Catalog=EGL_TEST;"); con.Open(); } } } vendername field contain data (MCCOLLISTER'S TRANSPORTATION) so how to pass this data

    Read the article

  • combobox with for each loop

    - by Mary
    Hi I am a student do anybody know after populating the combobox with the database values. How to display the same value in the text box. When I select a name in the combobox the same name should be displayed in the text box I am using seleted item. Here is the code. I am getting the error the following error using the foreach loop foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator' using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; namespace DBExample { public partial class Form1 : Form { private OleDbConnection dbConn; // Connectionn object private OleDbCommand dbCmd; // Command object private OleDbDataReader dbReader;// Data Reader object private Member aMember; private string sConnection; // private TextBox tb1; // private TextBox tb2; private string sql; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { try { // Construct an object of the OleDbConnection // class to store the connection string // representing the type of data provider // (database) and the source (actual db) sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=c:member.mdb"; dbConn = new OleDbConnection(sConnection); dbConn.Open(); // Construct an object of the OleDbCommand // class to hold the SQL query. Tie the // OleDbCommand object to the OleDbConnection // object sql = "Select * From memberTable Order " + "By LastName , FirstName "; dbCmd = new OleDbCommand(); dbCmd.CommandText = sql; dbCmd.Connection = dbConn; // Create a dbReader object dbReader = dbCmd.ExecuteReader(); while (dbReader.Read()) { aMember = new Member (dbReader["FirstName"].ToString(), dbReader["LastName"].ToString(), dbReader["StudentId"].ToString(), dbReader["PhoneNumber"].ToString()); // tb1.Text = dbReader["FirstName"].ToString(); // tb2.Text = dbReader["LastName"].ToString(); // tb1.Text = aMember.X().ToString(); //tb2.Text = aMember.Y(aMember.ID).ToString(); this.comboBox1.Items.Add(aMember.FirstName.ToString()); // this.listBox1.Items.Add(aMember.ToString()); // MessageBox.Show(aMember.ToString()); // Console.WriteLine(aMember.ToString()); } dbReader.Close(); dbConn.Close(); } catch (System.Exception exc) { MessageBox.Show("show" + exc); } } private void DbGUI_Load(object sender, EventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { this.textBox1.Text = comboBox1.SelectedItem.ToString(); textBox2.Text = string.Empty; foreach (var item in comboBox1.SelectedItem) textBox2.Text += item.ToString(); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } } }

    Read the article

  • Why does sending post data with WebRequest take so long?

    - by Paramiliar
    I am currently creating a C# application to tie into a php / MySQL online system. The application needs to send post data to scripts and get the response. When I send the following data username=test&password=test I get the following responses... Starting request at 22/04/2010 12:15:42 Finished creating request : took 00:00:00.0570057 Transmitting data at 22/04/2010 12:15:42 Transmitted the data : took 00:00:06.9316931 <<-- Getting the response at 22/04/2010 12:15:49 Getting response 00:00:00.0360036 Finished response 00:00:00.0360036 Entire call took 00:00:07.0247024 As you can see it is taking 6 seconds to actually send the data to the script, I have done further testing bye sending data from telnet and by sending post data from a local file to the url and they dont even take a second so this is not a problem with the hosted script on the site. Why is it taking 6 seconds to transmit the data when it is two simple strings? I use a custom class to send the data class httppostdata { WebRequest request; WebResponse response; public string senddata(string url, string postdata) { var start = DateTime.Now; Console.WriteLine("Starting request at " + start.ToString()); // create the request to the url passed in the paramaters request = (WebRequest)WebRequest.Create(url); // set the method to post request.Method = "POST"; // set the content type and the content length request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postdata.Length; // convert the post data into a byte array byte[] byteData = Encoding.UTF8.GetBytes(postdata); var end1 = DateTime.Now; Console.WriteLine("Finished creating request : took " + (end1 - start)); var start2 = DateTime.Now; Console.WriteLine("Transmitting data at " + start2.ToString()); // get the request stream and write the data to it Stream dataStream = request.GetRequestStream(); dataStream.Write(byteData, 0, byteData.Length); dataStream.Close(); var end2 = DateTime.Now; Console.WriteLine("Transmitted the data : took " + (end2 - start2)); // get the response var start3 = DateTime.Now; Console.WriteLine("Getting the response at " + start3.ToString()); response = request.GetResponse(); //Console.WriteLine(((WebResponse)response).StatusDescription); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); var end3 = DateTime.Now; Console.WriteLine("Getting response " + (end3 - start3)); // read the response string serverresponse = reader.ReadToEnd(); var end3a = DateTime.Now; Console.WriteLine("Finished response " + (end3a - start3)); Console.WriteLine("Entire call took " + (end3a - start)); //Console.WriteLine(serverresponse); reader.Close(); dataStream.Close(); response.Close(); return serverresponse; } } And to call it I use private void btnLogin_Click(object sender, EventArgs e) { // string postdata; if (txtUsername.Text.Length < 3 || txtPassword.Text.Length < 3) { MessageBox.Show("Missing your username or password."); } else { string postdata = "username=" + txtUsername.Text + "&password=" + txtPassword.Text; httppostdata myPost = new httppostdata(); string response = myPost.senddata("http://www.domainname.com/scriptname.php", postdata); MessageBox.Show(response); } }

    Read the article

  • Dialog created after first becomes unresponsive unless created first?

    - by Justin Sterling
    After creating the initial dialog box that works perfectly fine, I create another dialog box when the Join Game button is pressed. The dialog box is created and show successfully, however I am unable to type in the edit box or even press or exit the dialog. Does anyone understand how to fix this or why it happens? I made sure the dialog box itself was not the problem by creating and displaying it from the main loop in the application. It worked fine when I created it that way. So why does it error when being created from another dialog? My code is below. This code is for the DLGPROC function that each dialog uses. #define WIN32_LEAN_AND_MEAN #include "Windows.h" #include ".\Controllers\Menu\MenuSystem.h" #include ".\Controllers\Game Controller\GameManager.h" #include ".\Controllers\Network\Network.h" #include "resource.h" #include "main.h" using namespace std; extern GameManager g; extern bool men; NET_Socket server; extern HWND d; HWND joinDlg; char ip[64]; void JoinMenu(){ joinDlg = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_GETADDRESSINFO), NULL, (DLGPROC)GameJoinDialogPrompt); SetFocus(joinDlg); // ShowWindow(joinDlg, SW_SHOW); ShowWindow(d, SW_HIDE); } LRESULT CALLBACK GameJoinDialogPrompt(HWND Dialogwindow, UINT Message, WPARAM wParam, LPARAM lParam){ switch(Message){ case WM_COMMAND:{ switch(LOWORD(wParam)){ case IDCONNECT:{ GetDlgItemText(joinDlg, IDC_IP, ip, 63); if(server.ConnectToServer(ip, 7890, NET_UDP) == NET_INVALID_SOCKET){ LogString("Failed to connect to server! IP: %s", ip); MessageBox(NULL, "Failed to connect!", "Error", MB_OK); ShowWindow(joinDlg, SW_SHOW); break; }   } LogString("Connected!"); break; case IDCANCEL: ShowWindow(d, SW_SHOW); ShowWindow(joinDlg, SW_HIDE); break; } break; } case WM_CLOSE: PostQuitMessage(0); break; } return 0; } LRESULT CALLBACK GameMainDialogPrompt(HWND Dialogwindow, UINT Message, WPARAM wParam, LPARAM lParam){ switch(Message){ case WM_PAINT:{ PAINTSTRUCT ps; RECT rect; HDC hdc = GetDC(Dialogwindow);    hdc = BeginPaint(Dialogwindow, &ps); GetClientRect (Dialogwindow, &rect); FillRect(hdc, &rect, CreateSolidBrush(RGB(0, 0, 0)));    EndPaint(Dialogwindow, &ps);    break;  } case WM_COMMAND:{ switch(LOWORD(wParam)){ case IDC_HOST: if(!NET_Initialize()){ break; } if(server.CreateServer(7890, NET_UDP) != 0){ MessageBox(NULL, "Failed to create server.", "Error!", MB_OK); PostQuitMessage(0); return -1; } ShowWindow(d, SW_HIDE); break; case IDC_JOIN:{ JoinMenu(); } break; case IDC_EXIT: PostQuitMessage(0); break; default: break; } break; } return 0; } } I call the first dialog using the below code void EnterMenu(){ // joinDlg = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_GETADDRESSINFO), g_hWnd, (DLGPROC)GameJoinDialogPrompt);// d = CreateDialog(g_hInstance, MAKEINTRESOURCE(IDD_SELECTMENU), g_hWnd, (DLGPROC)GameMainDialogPrompt); } The dialog boxes are not DISABLED by default, and they are visible by default. Everything is set to be active on creation and no code deactivates the items on the dialog or the dialog itself.

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >