//ADDS NEW DATAGRIDVIEW ROW dgv.Rows.Add(txtFirstName.Text.ToString());
//ADDS THE SUBITEMS OF THE CURRENTLY ADDED ROW dgv.Rows[dgv.Rows.Count - 1].Cells[1].Value = txtLastName.Text.ToString(); dgv.Rows[dgv.Rows.Count - 1].Cells[2].Value = Convert.ToInt16(txtAge.Text);
//SELECT THE LAST ROW OF THE DATAGRIDVIEW dgv.Rows[dgv.Rows.Count - 1].Selected = true; } }
Directory listings are just HTML pages generated by a web server. Each web server generates these HTML pages in its own way because there is no standard way for a web server to list these directories.
The web server you'd like to list directories from must have directory browsing turned on to get this HTML representation of the files in its directories. So you can only get the directory listing if the HTTP server wants you to be able to.
[C#]
using System; using System.IO; using System.Net; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions;
namespace DirectoryListing { public partial class frmMainDownloader : Form { public frmMainDownloader() { InitializeComponent(); }
public static string GetDirectoryListingRegexForUrl(string url) { return "<a href=\".*\">(?<name>.*)</a>"; }
if (url.Equals("")) { MessageBox.Show("Please input the Webpage Url you want to parse.", "Invalid URL", MessageBoxButtons.OK, MessageBoxIcon.Error); txtUrl.Focus(); return; }
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string html = reader.ReadToEnd();
Regex regex = new Regex(GetDirectoryListingRegexForUrl(url)); MatchCollection matches = regex.Matches(html);
pbar.Maximum = matches.Count; pbar.Step = 100;
if (matches.Count > 0) { foreach (Match match in matches) { if (match.Success) { fileDir = match.Groups["name"].ToString();
if (fileDir != "Parent Directory") //EXCLUDES THE PARENT DIRECTORY { list.Items.Add(fileDir); pbar.Value ++;
The following snippet allows you to check if a process is already running in the background. If the process is already running it will prompt the user to whether start a new process or continue with the existing one that is running.
private void checkForDataInProgress() { if (!this.bConnectedToDatabase) return;
The following example loads the data of the Selected Row in a DataGridView control into a TextBox control in CSharp. As shown on the previous example Populate Data Into DataGridView using For-Loop in C#/CSharp, we'll use that method to fill our DataGridView with data. To begin with: 1.) Start start a new C# project. 2.) Add the following controls onto Form1.
(1) DataGridView Control
(2) TextBoxes
(2) Labels
3.) Open the Windows Form Designer and Update the DataGridView's generated code with the following.
// // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(12, 12); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.Size = new System.Drawing.Size(240, 221); this.dataGridView1.TabIndex = 0; this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
4.) Add the following codes into the Form1_Load() Event to fill the dataGridView control with data.
Random rand = new Random(); DataGridView dgv = this.dataGridView1;
In this tutorial, we'll be working on a real example on how to use Do...While Loop and a For...Loop Counter in VB.Net.
Example Description: 1. A customer will be asked to enter the prices of 4 items purchased using an input box (create a counter loop). 2. A tax rate of 7% will be a constant. 3. Subtotal, tax rate, and total will be displayed in labels. 4. An accumulator inside the loop will be used to calculate the subtotal. 5. A pre-test post-test do while loop shall be used to control the limit of entering price.
CODE:
Public Class Form1 Private Sub btnEnterPrices_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPrices.Click Dim Price As String Dim SubTotal As Double, Tax As Double, Total As Double Dim limit As String, newLimit As String Dim i As Integer, n As Integer, response As Integer
'Prompts the user the input the number of prices to be calculated limit = InputBox("Please enter the number of prices to calculate")
'Check user input for a valid number Do While IsNumeric(limit) = False limit = InputBox("Please enter the number of prices to calculate") Loop
'Start the counter up to the limit For i = 1 To limit 'Prompts for the price Price = InputBox("Please enter Price #" & i & ":", "Price # " & i)
'Check if the Price entered is valid If IsNumeric(Price) = False Then 'Display an error message until the user enters a valid price Do While IsNumeric(Price) = False MsgBox("Please input another a valid Price", vbExclamation, "Invalid Price") Price = InputBox("Please enter Price #" & i & ":", "Price # " & i) Loop Else 'Calculate sub-total SubTotal = SubTotal + Price End If
If i = limit Then
'If the limit is reached, 'prompt the user whether to enter additional prices to calculate response = MsgBox("Do you want to enter additional Price?", vbYesNo)
'If the user clicked Yes If response = vbYes Then
'Prompt a new limit newLimit = InputBox("Please enter number of additional Price to Calculate")
'Validate user input Do While IsNumeric(newLimit) = False newLimit = InputBox("Please enter number of additional Price to Calculate") Loop
'Start a new counter for the new limit For n = 1 To newLimit
'Prompt for the Price Price = InputBox("Please enter Price #" & i + n & ":", "Price # " & i + n)
'Validate User Input If IsNumeric(Price) = False Then
'Display a message while the price is not a valid number Do While IsNumeric(Price) = False MsgBox("Please input another a valid Price", vbExclamation, "Invalid Price") Price = InputBox("Please enter Price #" & i + n & ":", "Price # " & i + n) Loop Else 'Calculate Subtotal SubTotal = SubTotal + Price End If Next n End If End If Next i
'Calculate Tax and the Total Price Tax = Format(SubTotal * 0.07, "###.##") Total = Format(SubTotal + Tax, "###.##")
'START POPULATING DATA ROWS IN GRIDVIEW For i As Integer = 0 To 100 .Rows.Add() .RowHeadersVisible = False .Item(0, i).Value = "PC121113 " & i .Item(1, i).Value = "PRODUCT " & i .Item(2, i).Value = 100 - i .Item(3, i).Value = i Next
.SelectionMode = DataGridViewSelectionMode.FullRowSelect .BorderStyle = BorderStyle.Fixed3D .BackgroundColor = Color.White .RowsDefaultCellStyle.BackColor = Color.White .AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke .AllowUserToResizeRows = False End With
The example below is a simple way on how to Plot a Graph in Chart Windows Form Control using VB.Net.
Requirements: 1. Microsoft Visual Studio (In my case, I'm using Visual Studio 2010 Express Edition).
To Begin with: 1. Start your Microsoft Visual Basic 2010 Express. 2. In the New Project window, Choose "Windows Form Application" and name it to whatever you like or something like "Plot Graph" then Click "OK". 3. You must now be able to see the Form. On the toolbox Add the following controls onto the form and update its properties. a. Form: Name:=frmGraph b. (1) Chart: Name:=Chart1 c. (1) Textbox: Name:=txtData, Multiline:=True, Text:=30;52;57;57;68;93;129;173;209;232;240;232;217;196;169;141;116;98;86;80;78;76;76;79;81;83;86;91;95;97;95;93;95;99;103;105;106;107;110;116;120;122;123;124;127;132;137;139;137;136;132;126;124;122;117;113;110;105;97 d. (1) Button: Name:=btnPlot, Text:=&Plot
*Then arrange and re-size the controls as you can see below. But you can still orient it to whatever you want.
4. Now PressF7 to view the code editor window.
Code Blocks:
:namespace - We need to declare the namespace containing the methods and properties of the Chart Windows Form Control in order to use its properties and methods.
:frmGraph_Load() - When the form is loaded we do not want to see the Gridlines behind the plot so we'll disable it by setting the MajorGrid Property of the ChartAreas X and Y Axis Enabled to False and set it background to transparent.
Private Sub frmGraph_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load With Chart1.ChartAreas(0) .AxisX.MajorGrid.Enabled = False .AxisY.MajorGrid.Enabled = False .AxisX.MajorGrid.LineColor = Color.Coral .AxisY.MajorGrid.LineColor = Color.Coral .BackColor = Color.Transparent End With End Sub
:btnPlot_Click() - When the Plot button is clicked, we declare an Array and 2 collections of series values. CD = An array collection that holds the data we split from the data Textbox. s1 = Is our first series collection s2 = is our second series collection (Both have the same values since we only need to plot the Points and a Line.
Private Sub btnPlot_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlot.Click Dim CD As Array Dim s1 As New Series Dim s2 As New Series Dim xLab As Long
'GET data from the textbox CD = Split(txtData.Text, ";", -1)
Private Sub frmGraph_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load With Chart1.ChartAreas(0) .AxisX.MajorGrid.Enabled = False .AxisY.MajorGrid.Enabled = False .AxisX.MajorGrid.LineColor = Color.Coral .AxisY.MajorGrid.LineColor = Color.Coral .BackColor = Color.Transparent End With End Sub
Private Sub btnPlot_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlot.Click Dim CD As Array Dim s1 As New Series Dim s2 As New Series Dim xLab As Long
'GET data from the textbox CD = Split(txtData.Text, ";", -1)
The following codes will always Show the Selected Row of a DatagridView when the data is reloaded and will recall the state of the scrollbar by its scroll value..
private void datagridView1_Scroll(object sender, EventArgs e) { //WILL USE THE SCROLL VALUE LATER WHEN RELOADING THE DATAGRIDVIEW scrollVal = datagridView1.VerticalScrollingOffset; }
private void datagridView1_CellClick(object sender, DataGridViewCellEventArgs e) { //GETS THE INDEX OF THE CURRENT SELECTED ROW rowIndex = this.datagridView1.CurrentRow.Index; rowIndex = rowIndex != 0 ? lastRow = rowIndex : lastRow = rowIndex; }
private void reloadDatagridView() { //RELOADS DATA OF THE DATAGRIDVIEW datagridView1.Clear(); datagridView1.DataSource = "Your Data Table"; datagridView1.AutoGenerateColumns = true; datagridView1.MultiSelect = false; datagridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader); datagridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
datagridView1.Rows[lastRow].Selected = true;
int rowHeight = datagridView1.Rows.GetRowsHeight(DataGridViewElementStates.Selected);
HOW IT WORKS: scrollVal: Every time the user scroll's the control it will get the scrolling offset of the scroll bars.
lastRow: When the user clicks anywhere on the DatagridView's Cell it will get the Selected Row's Index and assign to lastRow variable. The lastRow variable will then be used as the Index of the Row that will be selected when the DatagridView is reloaded.
rowHeight: Get's the height of the DatagridViewRow's Selected element state.
.FirstDisplayedScrollingRowIndex = scrollVal / rowHeight: Set's the Scroll Value of the DatagridView when the data is reloaded.