Showing posts with label dotNet. Show all posts

How to Populate Data from Textbox to Datagridview in C#/CSharp

The following example allows you to populate data from a TextBox to DataGridView Control in C#/CSharp.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TextBoxToDataGridView
{


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

DataGridView dgv = this.dataGridView1;

//SET DATAGRIDVIEW PROPERTIES
dgv.AutoGenerateColumns = false;
dgv.AllowUserToAddRows = false;
dgv.RowHeadersVisible = false;
dgv.MultiSelect = false;

//SETS UP THE COLUMN HEADERS
dgv.Columns.Add("FName", "First Name");
dgv.Columns.Add("LName", "Last Name");
dgv.Columns.Add("Age", "Age");
}

private void btnAdd_Click(object sender, EventArgs e)
{
DataGridView dgv = this.dataGridView1;

//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;
}
}

}

Populate Website Directory Listing into ListView Control using C#/CSharp

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>";
}

private void btnFetchUrl_Click(object sender, EventArgs e)
{
string url = txtUrl.Text.ToString();
string fileDir = "";

if (url.Equals(""))
{
MessageBox.Show("Please input the Webpage Url you want to parse.", "Invalid URL", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUrl.Focus();
return;
}

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
ListView list = this.listView1;
ProgressBar pbar = this.progressBar1;

//CLEARS THE LISTVIEW ITEMS
list.Items.Clear();

//RESET PROGRESSBAR / PERCENTAGE VALUE
pbar.Value = 1;
pbar.Minimum = 1;
pbar.Visible = true;
lblPercent.Text = "";
lblPercent.Visible = true;

this.Refresh();

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 &gt; 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 ++;

lblPercent.Text = Convert.ToInt16((((double)pbar.Value / (double)pbar.Maximum) * 100 )).ToString() + " %";
}

this.Refresh();

}
}
}

//HIDE PROGRESSBAR AND PERCENTAGE
pbar.Visible = false;
lblPercent.Visible = false;
}
}
}

}

}

Populate Data into DataGridView using DataTable in C#/CSharp

The following snippet allows to populate data into DataGridView Control using DataTable in CSharp.

First, we establish a connection to our database.
string sConnect = "Data Source=" + Properties.Settings.Default.Server + ";Initial Catalog=" + Properties.Settings.Default.Database + ";";
if (Properties.Settings.Default.UseIntegratedSecurity)
sConnect += "Integrated Security=SSPI;";
else
sConnect += "User Id=" + Properties.Settings.Default.Username + ";Password=" + Properties.Settings.Default.Password + ";";
this.sSQLConnectString = sConnect;

This DataTable returns the Books Table.
public DataTable GetBooks()
{
string sql = "select * from Book order by ISBN13, ISBN10";

SqlDataAdapter da = new SqlDataAdapter(sql, sqlConnection);

try
{
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
}


We call this function to set prepare the DataTable and set it as the DataSource of the DataGridView Control.
private void loadBooks()
{
if (!this.bConnectedToDatabase)
return;
DataOperations dbo = new DataOperations(sSQLConnectString);
DataTable dt = dbo.GetBooks();
this.dgvBooks.DataSource = dt;
}

How to Kill or Start a New Background Process in C#/Csharp

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;

            Process proc = new Process();
            string sNumThreads = Properties.Settings.Default.NumberOfLocalThreads.ToString();
            string sProcArgs = "\"" + this.sSQLConnectString + "\" \"" + Properties.Settings.Default.XMLSaveDir + "\" \"" + Properties.Settings.Default.DLLDir + "\" " + sNumThreads;
            proc.StartInfo = new ProcessStartInfo(Properties.Settings.Default.DataImporterAppLocation, sProcArgs);
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.SynchronizingObject = this;
            Process[] procs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(proc.StartInfo.FileName));

            foreach (Process p in procs)
            {
                if (p.MainModule.FileName == proc.StartInfo.FileName)
                {

                    if (MessageBox.Show(this, "Data is currently being imported.\n\rIf you want to stop this import and begin a new import, click \"YES\"\n\r" +

                        "To allow the current data import to continue, click \"NO\"", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        proc.Exited += new EventHandler(proc_Exited);
                        proc.EnableRaisingEvents = true;
                        proc.Start();
                        this.tsDataCollectionLabel.Visible = true;
                        this.tsDataCollectionPGB.Visible = true;
                    }

                    return;
                }
            }
            proc.Exited += new EventHandler(proc_Exited);
            proc.EnableRaisingEvents = true;
            proc.Start();
            this.tsDataCollectionLabel.Visible = true;
            this.tsDataCollectionPGB.Visible = true;
        }

        void proc_Exited(object sender, EventArgs e)
        {
            this.tsDataCollectionLabel.Visible = false;
            this.tsDataCollectionPGB.Visible = false;
            checkForDataInProgress();
        }

Load Data of DataGridView's Selected Row to TextBox Control in C#/CSharp

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;
           
 //DATAGRIDVIEW SETTING
 dgv.AllowUserToAddRows = false;
 dgv.AllowUserToResizeRows = false;
 dgv.RowHeadersVisible = false;
 dgv.ReadOnly = true;
 dgv.MultiSelect = false;
 dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

 //ADD COLUMN HEADERS
 dgv.Columns.Add("Product", "Product");
 dgv.Columns.Add("Price", "Price");

 //ADD 10 ROWS
 dgv.Rows.Add(10);

 //NOW, POPULATE THE DATA INTO THE CELLS
 for (int i = 0; i < 10; i++)
 {
     double price = rand.Next(1, 30) * rand.NextDouble();

     dgv.Rows[i].Cells[0].Value = "Product " + i;
     dgv.Rows[i].Cells[1].Value = "$ " + price;
 }

 //CLEARS THE DEFAULT SELECTION WHICH IS THE FIRST ROW
 dgv.ClearSelection();

5.) Add the following code to handle on CellClick() Event of the dataGridView Control.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = this.dataGridView1;
    txtProduct.Text = dgv.SelectedRows[0].Cells[0].Value.ToString();
    txtPrice.Text = dgv.SelectedRows[0].Cells[1].Value.ToString();
}

6.) Build and Compile the Project. The project can also be downloaded here.

OUTPUT:


Populate Data Into DataGridView using For-Loop in C#/CSharp

The following example will populate data into a DataGridView Control using For-Loop.

To begin with:
1.) Create a new C# Project.
2.) Add a DataGridView Control onto Form1.
3.) Then copy the code below and paste on Form1_Load() event.


  Random rand = new Random();
DataGridView dgv = this.dataGridView1;

//DATAGRIDVIEW SETTING
dgv.AllowUserToAddRows = false;
dgv.RowHeadersVisible = false;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

//ADD COLUMN HEADERS
dgv.Columns.Add("Product", "Product");
dgv.Columns.Add("Price", "Price");

//ADD 10 ROWS
dgv.Rows.Add(10);

//NOW, POPULATE THE DATA INTO THE CELLS
for (int i = 0; i < 10; i++)
{
    double price = rand.Next(1, 30) * rand.NextDouble();

    dgv.Rows[i].Cells[0].Value = "Product " + i;
    dgv.Rows[i].Cells[1].Value = "$ " + price;
}

//CLEARS THE DEFAULT SELECTION WHICH IS THE FIRST ROW
dgv.ClearSelection();
4.) Build and Compile the project. The project can also be downloaded here.

OUTPUT:


How to use Do While Loop and a For Loop Counter in VB.Net

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, "###.##")

'Display results inside labels
lblSubTotal.Text = "$" & SubTotal
lblTax.Text = "$" & Tax
lblTotal.Text = "$" & Total

End Sub

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
End Class

Populate Data into ListView Control in VB.Net

The following example Populates Data into ListView Control in VB.Net when the form is loaded.

Add a ListView Control on your Visual Basic Project and add the following code snippet on Form Load event.

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        With ListView1

            .View = View.Details
            .FullRowSelect = True

            'Setup column headers
            .Columns.Add("Product", 100)
            .Columns.Add("Type", 100)
            .Columns.Add("Price", 50)

            For i As Integer = 0 To 10

                Dim lvi = .Items.Add("Product " & i)
                lvi.SubItems.Add("Type " & i)
                lvi.SubItems.Add("Price " & i)

            Next

        End With
End Sub
End Class

Populate Data into DataGridView Control using For-Loop in VB.Net


The following example shows how to Populate Data to DataGridView Control in VB.Net.


Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

With dgv
'SET COLUMN HEADERS
.Columns.Add("Product Code", "Product Code")
.Columns.Add("Product", "Product")
.Columns.Add("Quantity", "Quantity")
.Columns.Add("Price", "Price")

'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

End Sub

End Class


Implement a Graph from ASCII Data to Chart Windows Form Control using VB.NET

The example below is a simple way on how to Plot a Graph in Chart Windows Form Control using VB.Net.

Implement Graph on Chart Windows Form Control

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.

Form Controls Orientation

4. Now Press F7 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.

Imports System.Windows.Forms.DataVisualization.Charting

: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)

Chart1.Series.Clear()

s1.Name = "Series 1"
s1.ChartType = SeriesChartType.FastPoint
s2.Name = "Series 2"
s2.ChartType = SeriesChartType.FastLine

xLab = 1
'loop through each array and set series values
For Each d In CD
s1.Points.AddXY(xLab, d)
s2.Points.AddXY(xLab, d)
xLab = xLab + 1
Next

'Add update the chart with the series values
Chart1.Series.Add(s1)
Chart1.Series.Add(s2)

End Sub

Full Code:

Imports System.Windows.Forms.DataVisualization.Charting

Public Class frmGraph

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)

Chart1.Series.Clear()

s1.Name = "Series 1"
s1.ChartType = SeriesChartType.FastPoint
s2.Name = "Series 2"
s2.ChartType = SeriesChartType.FastLine

xLab = 1
'loop through each array and set series values
For Each d In CD
s1.Points.AddXY(xLab, d)
s2.Points.AddXY(xLab, d)
xLab = xLab + 1
Next

'Add update the chart with the series values
Chart1.Series.Add(s1)
Chart1.Series.Add(s2)

End Sub
End Class

5. Finally, build and run the project.

Always Show Selected Row of a DataGridView in C# / CSharp

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..

CODE:
private int scrollVal = 0, rowIndex = 0, lastRow = 0;

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);
       
        datagridView1.FirstDisplayedScrollingRowIndex = scrollVal / rowHeight;
 
        datagridView1.Refresh();
    }
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.