Search Results

Search found 4334 results on 174 pages for 'sender'.

Page 144/174 | < Previous Page | 140 141 142 143 144 145 146 147 148 149 150 151  | Next Page >

  • Populate table fields on query execution

    - by Jason
    I'm trying to build an ASP site that populates a Table based on the results of a selection in a ListBox. In order to do this, I've created a GridView table inside a div element. Currently the default behavior is to show all the items in the specified table in sortable order. However, I'd like to refine this further to allow for display of matches based on the results from the ListBox selection, but am not sure how to execute this. The ListBox fires off a OnSelectionChanged event to the method defined below and the GridView element is defined as <asp:GridView ID="dataListings" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="LinqDataSource1" OnDataBinding="ListBox1_SelectedIndexChanged"> protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { int itemSelected = selectTopics.SelectedIndex; string[] listing = null; switch (itemSelected)//assign listing the array of course numbers { case 0: break; case 1: listing = arts; break; case 2: listing = currentEvents; break; .... More cases here default: listing = arts; break; } using (OLLIDBDataContext odb = new OLLIDBDataContext()) { var q = from c in odb.tbl_CoursesAndWorkshops where listing.Contains(c.tbl_Course_Description.tbl_CoursesAndWorkshops.course_workshop_number) select c; dataListings.DataSource = q; dataListings.DataBind(); } } However, this method never gets fired. I can see a request being made when changing the selection, but setting a breakpoint at the method declaration does nothing at all. Based on this, setup, I have three related questions What do I need to modify to get the OnSelectionChanged event handler to fire? How can I alter the GridView area to be empty on page load? How do I send the results from the dataListings.DataBind() execution to show in the GridView?

    Read the article

  • Making a button click and process using javascript with Asp.Net

    - by user944919
    I'm having two buttons and one button is hidden. Now when I click the visible button I need to do two things 1.Open Iframe. 2.Automatically make the 2nd Button(Hidden)to be clicked. When the second button is clicked I need to display the message on top of the IFrame which I have mentioned as function showStickySuccessToast() Now I am able to open IFrame but I'm unable to make the Hidden button clicked automatically. This is what I'm having: <script type="text/javascript"> $(document).ready(function(){ $("#<%=Button1.ClientID%>").click(function(event){ $('#<%=TextBox1.ClientID%>').change(function () { $('#various3').attr('href', $(this).val()); }); }); function showStickySuccessToast() { $().toastmessage('showToast', { text: 'Finished Processing!', sticky: false, position: 'middle-center', type: 'success', closeText: '', close: function () { } }); } }) </script> Here are my two buttons how I'm working with: <a id="various3" href="#"><asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Button2_Click"/></a> <asp:Button ID="Button2" runat="server" Text="Button" Visible="False" OnClick="Button2_Click"/> And in the button2_Click event: Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "Script", "showStickySuccessToast();", True) End Sub

    Read the article

  • How to avoid GUI freeze when calling Beginthread API?

    - by isa
    Below just a simple race between 2 button in 2 threads, and this will freeze other components on the form. procedure moveButton1(); var I: Integer; begin for I := 0 to 6000 do Form1.Button1.Left := Form1.Button1.Left - 1; Form1.Caption := 'Button1 won!'; EndThread(0); end; procedure moveButton2(); var I: Integer; begin for I := 0 to 6000 do Form1.Button2.Left := Form1.Button2.Left - 1; Form1.Caption := 'Button2 won!'; EndThread(0); end; procedure TForm1.Button3Click(Sender: TObject); var thread1, thread2,tick : Integer; id1, id2 : LongWord; begin thread1 := BeginThread(nil, 0, Addr(moveButton1), nil, 0, id1); thread2 := BeginThread(nil, 0, Addr(moveButton2), nil, 0, id2); CloseHandle(thread1); CloseHandle(thread2); end;

    Read the article

  • WinForms: How to determine if window is no longer active (no child window has focus)?

    - by Marek
    My application uses multiple windows I want to hide one specific window in case the application loses focus (when the Active Window is not the application window) source I am handling the Deactivate event of my main form. private void MainForm_Deactivate(object sender, EventArgs e) { Console.WriteLine("deactivate"); if (GetActiveWindow() == this.Handle) { Console.WriteLine("isactive=true"); } else { Console.WriteLine("isactive=false"); } } [DllImport("user32.dll")] static extern IntPtr GetActiveWindow(); The output is always deactivate isactive=true I have observed the same behavior if a new window within my application receives focus and also if I click into a different application. I would expect GetActiveWindow to return the handle of the new active window when called from the Deactivate handler. Instead it always returns the handle of my application window. How is this possible? Is the Deactivate event handled "too soon"? (while the main form is still active?). How can I detect that my application has lost focus (my application window is not the active window) and another application gained it without running GetActiveWindow on a timer?

    Read the article

  • Updating a Database from DataBound Controls

    - by Avatar_Squadron
    Hi. I'm currently creating a WinForm in VB.NET bound to an access database. Basically what i have are two forms: one is a search form used to search the database, and the other is a details form. You run a search on the searchForm and it returns a list of Primary Keys and a few other identifying values. You then double click on the entry you want to view, and it loads the details form. The Details form has a collection of databound controls to display the data: mostly text boxes and checkboxs. The way i've set it up is i used the UI to build the form and then set the DataBindings Property of each control to "TblPropertiesBindingSource - " where value name is one of the values in the table (such as PropertyID or HasWoodFloor). Then, when you double click an entry in the searchform, I handle the event by parsing the Primary Key (PropertyID) out of the selected row and then storing this to the details form: Note: Detail is the details form that is opened to display the info Private Sub propView_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles propView.CellDoubleClick Dim detail As frmPropertiesDetail = New frmPropertiesDetail detail.id = propView.Rows(e.RowIndex).Cells(0).Value detail.Show() End Sub Then, upon loading the details form, it set's the filter on the BindSource as such: TblPropertiesBindingSource.Filter() = "PropertyID=" & id This works great so far. All the controls on the details form will display the correct info. The problem is updating changes. Scenario: If i have the user load the details for say, property 10001, it will show a description in a textBox named descriptionBox which is identical to the value of the description value of for that entry in the database. I want the user to then be able to change the text of the text box (which they can currently do) and click the save button (saveBut) and have the form update all the values in the controls to the database. Theorectically, it should do this as the controls are DataBound, thus i can avoid writing code that tells each entry in the database row to take the value of the aligned control. I've tried calleding PropertiesTableAdapter.Update(PropertiesBindingSource.DataSource), but that doesnt seem to do it.

    Read the article

  • UIButton addTarget method can not use in IOS 4.2

    - by Risma
    hi i have a UIButton made programmatically and i want to add the target and the action for that button. i have use method addTarget: action: forControlEvents: in IOS 4.1 this method is detected, but in 4.2 it didn't, here is my code float version = [[[UIDevice currentDevice] systemVersion] floatValue]; if(version <= 4.1){ moreButton = [[UIButton buttonWithType:UIButtonTypeCustom] initWithFrame:CGRectMake(6.3+5*widthSegment, 0.0, widthSegment, heightSegment)]; [moreButton addTarget:self action:@selector(getPopOverMore:) forControlEvents:UIControlEventTouchUpInside]; } else{ //version 4.2 NSLog(@"versi 4.2"); moreButton = [UIButton buttonWithType:UIButtonTypeCustom]; moreButton.frame = CGRectMake(6.3+7*widthSegment, 0.0, widthSegment, heightSegment); [moreButton addTarget:self action:@selector(getPopOverMore:) forControlEvents:UIControlEventTouchUpInside]; } and this is the action method : - (IBAction)getPopOverMore:(id)sender{ if(moreFileController == nil) { moreFileController = [[MoreFilePopController alloc] initWithStyle:UITableViewStylePlain]; moreFileController.delegate = self; moreFilePopOverController = [[UIPopoverController alloc] initWithContentViewController:moreFileController]; } CGRect frameMore = CGRectMake(6.3+5*widthSegment, 0.0, widthSegment, heightSegment); [moreFilePopOverController presentPopoverFromRect:frameMore inView:navBar permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES]; } any body know, what's wrong here??

    Read the article

  • My C# UploadFile method successfully uploads a file, but then my UI hangs...

    - by kyrathaba
    I have a simple WinForms test application in C#. Using the following method, I'm able to upload a file when I invoke the method from my button's Click event handler. The only problem is: my Windows Form "freezes". I can't close it using the Close button. I have to end execution from within the IDE (Visual C# 2010 Express edition). Here are the two methods: public void UploadFile(string FullPathFilename) { string filename = Path.GetFileName(FullPathFilename); try { FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(_remoteUser, _remotePass); StreamReader sourceStream = new StreamReader(FullPathFilename); byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); request.ContentLength = fileContents.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(fileContents, 0, fileContents.Length); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); response.Close(); requestStream.Close(); sourceStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload error"); } finally { } } which gets called here: private void btnUploadTxtFile_Click(object sender, EventArgs e) { string username = "my_username"; string password = "my_password"; string host = "ftp://mywebsite.com"; try { clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password); client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Upload problem"); } }

    Read the article

  • Security considerations processing emails

    - by Timmy O' Tool
    I have process that will be reading emails from an account. The objective of the process is saving to a database those emails with image(s) as attachments. I will be saving sender, subject body and image path (the image will be saved on the process). I will be showing this information on a page so I would like to know all (or most of them :) ) security aspects to cover. I plan to sanitize the subject and body of the email. I can remove most of the tags, probably it would be enough keeping the <p> tag. I'm not sure if I can trust just in a sanitizer. I would like to HTML encode everything except for the <p> tag after sanitize, just in case. Any suggestion? I'm only accepting images as attachment as I said above, any security risk I have to take into account in relation to the attachment? Thanks!

    Read the article

  • FormStartPosition.CenterParent does not work

    - by kol
    In the following code, only the second method works for me (.NET 4.0). FormStartPosition.CenterParent does not center the child form over its parent. Why? Source: this SO question using System; using System.Drawing; using System.Windows.Forms; class Program { private static Form f1; public static void Main() { f1 = new Form() { Width = 640, Height = 480 }; f1.MouseClick += f1_MouseClick; Application.Run(f1); } static void f1_MouseClick(object sender, MouseEventArgs e) { Form f2 = new Form() { Width = 400, Height = 300 }; switch (e.Button) { case MouseButtons.Left: { // 1st method f2.StartPosition = FormStartPosition.CenterParent; break; } case MouseButtons.Right: { // 2nd method f2.StartPosition = FormStartPosition.Manual; f2.Location = new Point( f1.Location.X + (f1.Width - f2.Width) / 2, f1.Location.Y + (f1.Height - f2.Height) / 2 ); break; } } f2.Show(f1); } }

    Read the article

  • How can I retain the data stored in plist from UITextField when application is restarted ?

    - by srikanth rongali
    I am using the plist to store the data entered in the UITextFields. But, when I restart my application all the data entered previously was deleted. How can I retain the data in the Plist. I have a UITableView and when a cell is touched a view appears with two UITextFields. nameField and descriptionField. I stored the data in this way. My code is. -(void)save:(id)sender { indexOfDataArray = temp; //the cell selected in table view. NSString *string1 = [[NSString alloc]init]; NSString *string2 = [[NSString alloc]init]; string1 = nameField.text; string2 = descriptionField.text; NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:string2, string1, nil]; [myArray addObject:myDict]; //myArray is NSMutableArray declared in tableViewController class. //[myArray insertObject:myDict atIndex:indexOfDataArray]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"tableVideoData.plist"]; [myArray writeToFile:path atomically:YES]; UIAlertView *alertMesage = [[UIAlertView alloc] initWithTitle: @"Save Alert" message:@"The data entered is saved" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil] ; [alertMesage show]; [alertMesage release]; } When I am using the [myArray insertObject:myDict atIndex:indexOfDataArray]; It is giving the error *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray insertObject:atIndex:]: index (2) beyond bounds (1)' So I used [myArray addObject:myDict]; Please help me, how can I retain the data in plist. Thank You.

    Read the article

  • The same property and procedure in different Classes. How they can be accessed ?

    - by lyborko
    Hi, I created several new objects TMyMemo = class (TMemo) private FYahoo = Integer; procedure SetYahoo(Value:integer) public procedure Google(A,B:integer; S:string); published property Yahoo:integer read FYahoo write SetYahoo; end; TMyPaintbox = class (TPaintbox) private FYahoo = Integer; procedure SetYahoo(Value:integer) public procedure Google(A,B:integer; S:string); published property Yahoo:integer read FYahoo write SetYahoo; end; TMyButton = class (TButton) private FYahoo = Integer; procedure SetYahoo(Value:integer) public procedure Google(A,B:integer; S:string); published property Yahoo:integer read FYahoo write SetYahoo; end; . . . These Controls are placed on Form1. Is there a way, how can I change the same property (Yahoo) and run the procedure (Google), which is declared in different objects (inheritance is not possible) ? procedure Form1.Button1Click(Sender:TObject); var i:integer; begin for i:=0 to Form1.ControlCount-1 do begin Controls[i].Google(4,5, 'Web'); // this should be changed somehow Controls[i].Yahoo:=6; // this should be changed somehow end; end; end; Thanks

    Read the article

  • ExecuteNonQuery: Connection property has not been initialized

    - by 20151012
    I get an error in my code: The error point at dbcom.ExecuteNonQuery();. Code(connection) public admin_addemp() { InitializeComponent(); con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\EMPS.accdb;Persist Security Info=True"); con.Open(); ds.Tables.Add(dt); ds.Tables.Add(dt2); } Code (Save button) private void save_btn_Click(object sender, EventArgs e) { OleDbCommand check = new OleDbCommand(); check.Connection = con; check.CommandText = "SELECT COUNT(*) FROM employeeDB WHERE ([EmployeeName]=?)"; check.Parameters.AddWithValue("@EmployeeName", tb_name.Text); if (Convert.ToInt32(check.ExecuteScalar()) == 0) { dbcom2 = new OleDbCommand("SELECT EmployeeID FROM employeeDB WHERE EmployeeID='" + tb_id.Text + "'", con); OleDbParameter param = new OleDbParameter(); param.ParameterName = tb_id.Text; dbcom.Parameters.Add(param); OleDbDataReader read = dbcom2.ExecuteReader(); if (read.HasRows) { MessageBox.Show("The Employee ID '" + tb_id.Text + "' already exist. Please choose another Employee ID."); read.Dispose(); read.Close(); } else { string q = "INSERT INTO employeeDB (EmployeeID, EmployeeName, IC, Address, State, " + " Postcode, DateHired, Phone, ManagerName) VALUES ('" + tb_id.Text + "', " + " '" + tb_name.Text + "', '" + tb_ic.Text + "', '" + tb_add1.Text + "', '" + cb_state.Text + "', " + " '" + tb_postcode.Text + "', '" + dateTimePicker1.Value + "', '" + tb_hp.Text + "', '" + cb_manager.Text + "')"; dbcom = new OleDbCommand(q, con); dbcom.ExecuteNonQuery(); MessageBox.Show("New Employee '" + tb_name.Text + "'- Successfuly Added."); } } else { MessageBox.Show("Employee name '" + tb_name.Text + "' already added into the database"); } ds.Dispose(); } I'm using Microsoft Access 2010 as my database and this is stand alone system. Please help me.

    Read the article

  • Make datalist into 3 x 3

    - by unknown
    This is my code behind for products page. The prodblem is that my datalist will fill in new items whenever I add a new object in the website. So may I know how to add the codes in so that I can make the datalist into 3x3. Thanks. Code behind Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim Product As New Product Dim DataSet As New DataSet Dim pds As New PagedDataSource DataSet = Product.GetProduct Session("Dataset") = DataSet pds.PageSize = 4 pds.AllowPaging = True pds.CurrentPageIndex = 1 Session("Page") = pds If Not Page.IsPostBack Then UpdateDatabind() End If End Sub Sub UpdateDatabind() Dim DataSet As DataSet = Session("DataSet") If DataSet.Tables(0).Rows.Count > 0 Then pds.DataSource = DataSet.Tables(0).DefaultView Session("Page") = pds dlProducts.DataSource = DataSet.Tables(0).DefaultView dlProducts.DataBind() lblCount.Text = DataSet.Tables(0).Rows.Count End If End Sub Private Sub dlProducts_UpdateCommand(source As Object, e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles dlProducts.UpdateCommand dlProducts.DataBind() End Sub Public Sub PrevNext_Command(source As Object, e As CommandEventArgs) Dim pds As PagedDataSource = Session("Page") Dim CurrentPage = pds.CurrentPageIndex If e.CommandName = "Previous" Then If CurrentPage < 1 Or CurrentPage = pds.IsFirstPage Then CurrentPage = 1 Else CurrentPage -= 1 End If UpdateDatabind() ElseIf e.CommandName = "Next" Then If CurrentPage > pds.PageCount Or CurrentPage = pds.IsLastPage Then CurrentPage = CurrentPage Else CurrentPage += 1 End If UpdateDatabind() End If Response.Redirect("Products.aspx?PageIndex=" & CurrentPage) End Sub this is my code for product.vb Public Function GetProduct() As DataSet Dim strConn As String strConn = ConfigurationManager.ConnectionStrings("HomeFurnitureConnectionString").ToString Dim conn As New SqlConnection(strConn) Dim strSql As String 'strSql = "SELECT * FROM Product p INNER JOIN ProductDetail pd ON p.ProdID = pd.ProdID " & _ ' "WHERE pd.PdColor = (SELECT min(PdColor) FROM ProductDetail as pd1 WHERE pd1.ProdID = p.ProdID)" Dim cmd As New SqlCommand(strSql, conn) Dim ds As New DataSet Dim da As New SqlDataAdapter(cmd) conn.Open() da.Fill(ds) conn.Close() Return ds End Function

    Read the article

  • Make password case unsensitive in shared ASP.Net membership tables web ap

    - by bill
    Hi all, i have two webapps.. that share ASP.Net membership tables. Everything works fine except i cannot remove case-sensitivity in one of the apps the way i am doing it in the other. in the non-working app void Login1_LoggingIn(object sender, LoginCancelEventArgs e) { string username = Login1.UserName.Trim(); if (!string.IsNullOrEmpty(username)) { MembershipUser user = Membership.GetUser(username); if (user != null) { // Only adjust the UserName if the password is correct. This is more secure // so a hacker can't find valid usernames if we adjust the case of mis-cased // usernames with incorrect passwords. string password = Login1.Password.ToUpper(); if (Membership.ValidateUser(user.UserName, password)) { Login1.UserName = user.UserName; } } } } is not working. the password is stored as all upper case. Converted at the time the membership user is created! So if the password is PASSWORD, typing PASSWORD allows me to authenticate. but typing password does not! Even though i can see the string being sent is PASSWORD (converted with toUpper()). I am at a complete loss on this.. in the other app i can type in lower or upper or mixed and i am able to authenticate. In the other app i am not using the textboxes from the login control though.. not sure if this is making the difference??

    Read the article

  • ArgumentOutOfRangeException was unhandled by user code - (ASP .net)

    - by ASr..
    I use a GridView to display the records from the database. Also i've attached a Hyperlink to the GridView using TemplateField. When I try to add "onclick" attribute to the HyperLink inside the RowDateBound event, I get the following error.. GridView1.DataKeys[e.Row.RowIndex].Value = 'GridView1.DataKeys[e.Row.RowIndex]' threw an exception of type 'System.ArgumentOutOfRangeException' Message = "Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index" This is the coding inside the RowDataBound mentod.. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1"); //The following line makes the error HyperLink1.Attributes.Add("onclick", "ShowMyModalPopup('" + GridView1.DataKeys[e.Row.RowIndex].Value + "')"); } } This is "ShowMyModalPopup" function in javascript <script type="text/javascript"> function ShowMyModalPopup(userpk) { var modal = $find('ModalPopupExtender1'); modal.show(); WebService.FetchOneUser(userpk,DisplayResult); } </script> Can anyone please explain me why this error occurs.. Many thanks in advance..

    Read the article

  • Cross Thread problem C#

    - by Frederik Witte
    Hello people - I got this code (lg_log is a listbox, and i want it to log the start_server.bat) Here is the code i got: public void bt_play_Click(object sender, EventArgs e) { lg_log.Items.Add("Starting Mineme server .."); string directory = Directory.GetCurrentDirectory(); var info = new ProcessStartInfo(directory + @"\start_base.bat") {UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true, WorkingDirectory = directory + @"\Servers\Base"}; var proc = new Process { StartInfo = info, EnableRaisingEvents = true }; proc.OutputDataReceived += (obj, args) => { if (args.Data != null) { lg_log.Items.Add(args.Data); } }; proc.Start(); proc.BeginOutputReadLine(); lg_log.Items.Add("Server is now running!"); proc.WaitForExit(); } When i run this, i'll get an error .. Anybody can help me? I'll rate the answer up! :D Edit: The error i get is this: System.InvalidOperationException Hope it helps :) The error comes at the lg_log.Items.Add(args.Data); code line

    Read the article

  • Events convention - I don't get it

    - by bobjink
    My class with an event: public class WindowModel { public delegate void WindowChangedHandler(object source, WindowTypeEventArgs e); public event WindowChangedHandler WindowChanged; public void GotoWindow(WindowType windowType) { this.currentWindow = windowType; this.WindowChanged.Invoke(this, new WindowTypeEventArgs(windowType)); } } Derived event class: public class WindowTypeEventArgs : EventArgs { public readonly WindowType windowType; public WindowTypeEventArgs(WindowType windowType) { this.windowType = windowType; } } Some other class that register it to the event: private void SetupEvents() { this.WindowModel.WindowChanged += this.ChangeWindow; } private void ChangeWindow(object sender, WindowTypeEventArgs e) { //change window } What have I gained from following the .Net convention? It would make more sense to have a contract like this public delegate void WindowChangedHandler(WindowType windowType); public event WindowChangedHandler WindowChanged; Doing it this way, I don't need to create a new class and is easier to understand. I am not coding a .Net library. This code is only going to be used in this project. I like conventions but am I right when I say that in this example it does not make sense or have i missunderstood something?

    Read the article

  • Displaying cookies as key=value for all domains?

    - by OverTheRainbow
    Hello, This question pertains to the use of the cookie-capable WebClient derived class presented in the How can I get the WebClient to use Cookies? question. I'd like to use a ListBox to... 1) display each cookie individually as "key=value" (the For Each loop displays all of them as one string), and 2) be able to display all cookies, regardless of the domain from which they came ("www.google.com", here): Imports System.IO Imports System.Net Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim webClient As New CookieAwareWebClient Const URL = "http://www.google.com" Dim response As String response = webClient.DownloadString(URL) RichTextBox1.Text = response 'How to display cookies as key/value in ListBox? 'PREF=ID=5e770c1a9f279d5f:TM=1274032511:LM=1274032511:S=1RDPaKJKpoMT9T54 For Each mycc In webClient.cc.GetCookies(New Uri(URL)) ListBox1.Items.Add(mycc.ToString) Next End Sub End Class Public Class CookieAwareWebClient Inherits WebClient Public cc As New CookieContainer() Private lastPage As String Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest Dim R = MyBase.GetWebRequest(address) If TypeOf R Is HttpWebRequest Then With DirectCast(R, HttpWebRequest) .CookieContainer = cc If Not lastPage Is Nothing Then .Referer = lastPage End If End With End If lastPage = address.ToString() Return R End Function End Class Thank you.

    Read the article

  • please help me for performing serch in my program

    - by Abid
    i want to perform searching in my programe.. i have my class in which i have made a function i.e. public DataTable Search() { string SQL = "Select * from Customer where " + mField + " like '%" + mValue + "%'"; DataTable dt = new DataTable(); dt = dm.GetData(SQL); return (dt); } in which i have made setters and getters for mField and mValue.. where dm is the object of class Datamanagement in which i have made a function GetData i.e. public DataTable GetData(string SQL) { SqlCommand command = new SqlCommand(); SqlDataAdapter dbAdapter = new SqlDataAdapter(); DataTable DataTable = new DataTable(); command.Connection = clsConnection.GetConnection(); command.CommandText = SQL; dbAdapter.SelectCommand = command; dbAdapter.Fill(DataTable); return (DataTable); } and behind the search button, i have written.. private void btnfind_Click(object sender, EventArgs e) { //cust is the object of class customer// if (tbCustName.Text != "") { cust.Field="CustName"; cust.Value = tbCustName.Text; } else if (tbAddress.Text != "") { cust.Value = tbAddress.Text; cust.Field="Address"; } else if (tbEmail.Text != "") { cust.Value = tbEmail.Text; cust.Field="Email"; } else if (tbCell.Text != "") { cust.Value = tbCell.Text; cust.Field = "Cell"; } DataTable dt = new DataTable(); dt = cust.Search(); dgCustomer.DataSource = dt; RefreshGrid(); } where my referesh grid fuction does that : private void RefreshGrid() { DataTable dt = new DataTable(); dt = cust.GetCustomers(); dgCustomer.DataSource = dt; } but this is not working.. i dont knw y.. please help..

    Read the article

  • Assigning values to the lable through database depending on listbox values

    - by SurajVitekar
    I want to assign the values of five labels from database regarding to values selected in listbox. The db query returns single column with multiple records. Please help. I'm working with C# 2010 and MS SQL. My current code is: private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { try { String c1, c2; c1 = "NULL"; MessageBox.Show("LB index :"+listBox1.SelectedIndex.ToString()); //p = listBox1.SelectedItem.ToString(); SqlConnection con = new SqlConnection(); con.ConnectionString = "Data Source=localhost;Initial Catalog=eVoting;Integrated Security=True;Pooling=False"; con.Open(); MessageBox.Show("List bOx sect :"+listBox1.SelectedValue.ToString()); SqlCommand cmd = new SqlCommand("select Firstname from candidates where position ='" + listBox1.SelectedValue.ToString() + "'", con); int index = 0; SqlDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { if (index == 0) { c1 = reader[index].ToString(); radioButton1.Text = c1; } if (index == 1) { c1 = reader[index].ToString(); radioButton2.Text = c1; } if (index == 2) { c1 = reader[index].ToString(); radioButton3.Text = c1; } if (index == 3) { c1 = reader[index].ToString(); radioButton4.Text = c1; } if (index == 4) { c1 = reader[index].ToString(); radioButton4.Text = c1; } if (index == 5) { c1 = reader[index].ToString(); radioButton5.Text = c1; } MessageBox.Show("c1 :" + c1); index++; } } catch (Exception E) { } }

    Read the article

  • How to focus a control in an MDIParent when all child windows have closed?

    - by Tim Gradwell
    I have a control in my parent mdi form which I wish to be given the focus if all mdi children have closed. I've tried hooking into the child form's FormClosed event and setting the focus from there but when I test it, my control is not left with focus when I close the mdi child. Can anyone tell me what I'm missing? In the sample below, "first focus" gets hit and does its job correctly (if I comment out the first focus line, my tree does not get focus on startup, so it must be doing its job, right?) Unfortunately, even though "second focus" gets hit, my tree does not end up with the focus when I close the child window. Sample using System; using System.Windows.Forms; namespace mdiFocus { class ParentForm : Form { public ParentForm() { IsMdiContainer = true; tree = new TreeView(); tree.Nodes.Add("SomeNode"); tree.Dock = DockStyle.Left; Controls.Add(tree); } protected override void OnShown(EventArgs e) { Form child = new Form(); child.MdiParent = this; child.Show(); child.FormClosed += new FormClosedEventHandler(child_FormClosed); tree.Focus(); // first focus works ok } void child_FormClosed(object sender, FormClosedEventArgs e) { tree.Focus(); // second focus doesn't seem to work, even though it is hit :( } TreeView tree; } static class Program { [STAThread] static void Main() { Application.Run(new ParentForm()); } } }

    Read the article

  • Can this line of code really throw an IndexOutOfRange exception?

    - by Jonathan M
    I am getting an IndexOutOfRange exception on the following line of code: var searchLastCriteria = (SearchCriteria)Session.GetSafely(WebConstants.KeyNames.SEARCH_LAST_CRITERIA); I'll explain the above here: SearchCriteria is an Enum with only two values Session is the HttpSessionState GetSafely is an extension method that looks like this: public static object GetSafely(this HttpSessionState source, string key) { try { return source[key]; } catch (Exception exc) { log.Info(exc); return null; } } WebConstants.KeyNames.SEARCH_LAST_CRITERIA is simply a constant I've tried everything to replicate this error, but I cannot reproduce it. I am beginning to think the stack trace is wrong. I thought perhaps the exception was actually coming from the GetSafely call, but it is swallowing the exceptions, so that can't be the case, and even if it was, it should show up in the stack trace. Is there anything in the line of code above that could possible throw an IndexOutOfRange exception? I know the line will throw an NullReferenceException if GetSafely returns null, and it will also throw an InvalidCastException if it returns anything that cannot be cast to SearchCriteria, but an IndexOutOfRange exception? I'm scratching my head here. Here is the stack trace: $LOG--> 2010-06-11 07:01:33,814 [ERROR] SERVERA (14) Web.Global - Index was outside the bounds of the array. System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array. at IterateSearchResult(Boolean next) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 242 at nextAccountLink_Click(Object sender, EventArgs e) in C:\Projects\Web\UserControls\AccountHeader.ascx.cs:line 232

    Read the article

  • insert data using sqlite issue on iphone ( not reflecting on table)

    - by prajakta
    i can insert my data but i cant show them on my table view ..i did [tableview reload data] but of no success here is my code -(void)gButtonTapped:(id)sender { NSLog(@"right nav bar button is hit%@ ",storePaths); //[self readAnimalsFromDatabase2]; appDelegate = (DatabaseTestAppDelegate *)[[UIApplication sharedApplication] delegate]; sqlite3 *database; sqlite3_stmt *compiled_statement1; if(sqlite3_open([storePaths UTF8String], &database) == SQLITE_OK) { //const char *sqlStatement = NSString *newQuery = [NSString stringWithFormat:@"insert into cat_tbl (cat_id,names,imgs) values ('12','test1','r.png')"]; // NSString *newQuery = [NSString stringWithFormat:@"select * from list_tbl"]; const char *sql = [newQuery cStringUsingEncoding:NSASCIIStringEncoding]; NSLog(@"update query is %@",newQuery); if(sqlite3_prepare_v2(database, sql, -1, &compiled_statement1, NULL) == SQLITE_OK) { int result = sqlite3_step(compiled_statement1); sqlite3_reset(compiled_statement1); NSLog(@"result %d", result); if(result != SQLITE_ERROR) { int lastInsertId = sqlite3_last_insert_rowid(database); NSLog(@"x %d", lastInsertId); } } } sqlite3_finalize(compiled_statement1); sqlite3_close(database); [tabelView reloadData];// this is also not working }

    Read the article

  • Are background threads a bad idea? Why?

    - by Matt Grande
    So I've been told what I'm doing here is wrong, but I'm not sure why. I have a webpage that imports a CSV file with document numbers to perform an expensive operation on. I've put the expensive operation into a background thread to prevent it from blocking the application. Here's what I have in a nutshell. protected void ButtonUpload_Click(object sender, EventArgs e) { if (FileUploadCSV.HasFile) { string fileText; using (var sr = new StreamReader(FileUploadCSV.FileContent)) { fileText = sr.ReadToEnd(); } var documentNumbers = fileText.Split(new[] {',', '\n', '\r'}, StringSplitOptions.RemoveEmptyEntries); ThreadStart threadStart = () => AnotherClass.ExpensiveOperation(documentNumbers); var thread = new Thread(threadStart) {IsBackground = true}; thread.Start(); } } (obviously with some error checking & messages for users thrown in) So my three-fold question is: a) Is this a bad idea? b) Why is this a bad idea? c) What would you do instead?

    Read the article

  • User switching without logging off

    - by mrh1967
    We need to switch users without logging off so we can remotely administrate a PC running with a limited user that will disconnect from the VPN if the user logs off. I've got this working by killing the explorer process and then running explorer.exe with the administrator user credentials as the following code shows: private void btnOk_Click(object sender, EventArgs e) { IntPtr tokenHandle = new IntPtr(0); if (LogonUser("administrator", Environment.UserDomainName, txtPassword.Text, 3, 0, ref tokenHandle)) { ProcessStartInfo psi = new ProcessStartInfo(@"C:\Windows\explorer.exe"); psi.UserName = "administrator"; char[] pword = txtPassword.Text.ToCharArray(); psi.Password = new System.Security.SecureString(); foreach (char c in pword) { psi.Password.AppendChar(c); } psi.UseShellExecute = false; psi.LoadUserProfile = true; restartExplorer(psi); this.Close(); } else { MessageBox.Show("Wrong password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void restartExplorer(ProcessStartInfo psi) { Process[] procs = System.Diagnostics.Process.GetProcesses(); foreach (Process p in procs) { if (p.ProcessName == "explorer") { p.Kill(); break; } } System.Diagnostics.Process.Start(psi); } [DllImport("advapi32.dll", SetLastError = true)] public extern static bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); This code and similar code that does the same but makes the ProcessStartInfo for the limited user works perfectly and allows changing between the limited and administrator accounts without disconnecting the VPN but it has one problem - If we use this to change to the administrator user, make some changes to the system, then change back to the limited user all works ok until the limited user logs off when a blank desktop is displayed until CTRL-ALT-DEL is pressed and the user is logged off again. Because we block CTRL-ALT-DEL the PC effectively hangs until it is powered off. Does anyone know how to stop this from happening so we can change users without the PC hanging when they log off?

    Read the article

< Previous Page | 140 141 142 143 144 145 146 147 148 149 150 151  | Next Page >