This Program Helps You To Insert Data Grid View Values To A Database.
In My Example I'm Considering A Data Grid View With Three Columns Named As ItemNo , ItemName, Qty.In My Example I Wanted To Insert All The DataGridView Rows To A Table Called Items Which Has ItemNo, ItemName, Qty Fields.Insertion Must Happened After Clicking The Save Button.
Make Sure Data Types In The Data Grid View Are Similar To The Data Types In The Database Table.
First Create A New Project and Add A DataGridView and A Button To It.Make Sure Your Data Grid View Id As MyDataGridView and Button Id As Save.Then Add Three Columns To That.You Can Add Columns To The DataGridView From Either Properties Window or from Code.
Before Doing The Codes Make Sure You Have The Sql Server Class As Follows.
(if you have any problem in SQL Connection refer to following post
http://easycodestuff.blogspot.com/2014/01/secure-best-sql-server-connection-for-c.html)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
namespace DataGridViewExample
{
class DBConnection
{
string strconnection = "Server=localhost;Uid=root;Pwd=;Database=yourdatabase;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sqlda = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlda = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
sqlda.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
Make Sure Your Form Class Start With Following Code Lines.
namespace DataGridViewExample
{
class test
{
private string query = "";
DBConnection connection = new DBConnection();
DataTable dt = new DataTable();
Finally You Have To Do Is Reading All The Rows Of The Data Grid View Thorough A Loop and Calling The Insert Query Inside The Same Loop.Following Code Unit Will Help You That.
private void BtnSave_Click(object sender, EventArgs e)//Save Button
{
for (int i = 0; i < MyDataGridView.RowCount; i++) // Run Until End Of MyDataGridView
{
query = "INSERT INTO Items(ItemNo,ItemName,Qty) VALUES('" +
MyDataGridView.Rows[i].Cells[0].Value.ToString() + "','" +
MyDataGridView.Rows[i].Cells[1].Value.ToString() + "','" +
MyDataGridView.Rows[i].Cells[2].Value.ToString() + "')";
connection.connect();
connection.QryCommand(query);
}
}
Jan 10, 2014
C# How to Convert a String to a Number
decimal - ToDecimal(stringvariable)
float - ToSingle(stringvariable)
double - ToDouble(stringvariable)
int - ToInt(stringvariable)
string stringvalriable="1001";
int intvariable = Convert.ToInt(stringvariable);
float - ToSingle(stringvariable)
double - ToDouble(stringvariable)
int - ToInt(stringvariable)
string stringvalriable="1001";
int intvariable = Convert.ToInt(stringvariable);
Jan 9, 2014
C# Load Data Into Data Grid On ComboBox Select Changed
private void COMBOBOXNAME_SelectedIndexChanged(object sender, EventArgs e)
{
string Selecteditem = COMBOBOXNAME.Items[COMBOBOXNAME.SelectedIndex].ToString();
string ConnectionString = @"Server=localhost;Database=dbname;Trusted_Connection=True";
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex )
{
MessageBox.Show(ex.Message);
}
SqlCommand command = con.CreateCommand()
command.CommandText = "SELECT * from Test";
int iCount =0;
SqlDataReader reader = command.ExecuteReader();
DGName.Rows.Clear();
while (reader.Read())
{
DGName.Rows.Add();
DGName.Rows[iCount].Cells[0].Value = iCount + 1; // row number will be added
DGName.Rows[iCount].Cells[1].Value = reader["DBColumnName"].ToString();
DGName.[iCount].Cells[2].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[3].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[4].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[5].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[6].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[7].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[8].Value = reader["DBColumnName"].ToString();
iCount++;
}
reader.Close();
con.Close();
}
//DGName : Wnter Your Data Grid Name
//iCount : Counts The Rows
//COMBOBOXNAME : Enter Your ComboBoxName
{
string Selecteditem = COMBOBOXNAME.Items[COMBOBOXNAME.SelectedIndex].ToString();
string ConnectionString = @"Server=localhost;Database=dbname;Trusted_Connection=True";
SqlConnection con = new SqlConnection(ConnectionString);
try
{
con.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex )
{
MessageBox.Show(ex.Message);
}
SqlCommand command = con.CreateCommand()
command.CommandText = "SELECT * from Test";
int iCount =0;
SqlDataReader reader = command.ExecuteReader();
DGName.Rows.Clear();
while (reader.Read())
{
DGName.Rows.Add();
DGName.Rows[iCount].Cells[0].Value = iCount + 1; // row number will be added
DGName.Rows[iCount].Cells[1].Value = reader["DBColumnName"].ToString();
DGName.[iCount].Cells[2].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[3].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[4].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[5].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[6].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[7].Value = reader["DBColumnName"].ToString();
DGName.Rows[iCount].Cells[8].Value = reader["DBColumnName"].ToString();
iCount++;
}
reader.Close();
con.Close();
}
//DGName : Wnter Your Data Grid Name
//iCount : Counts The Rows
//COMBOBOXNAME : Enter Your ComboBoxName
Jan 7, 2014
C# SQL Server Connection -Secure & Best
To Create A Highly Secure SqlServer Connection We Must Have Connection String and All The Sql Stuff In Separate Class...
Without Doing Anything Related SQL Stuff In The Current Class We Can Create A Separate Class For That And We Can Handle From Their...
Create A New Class Call DBConnect and Paste The Following Code
This Class Controls All The Sql Related Stuff
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace MyProject
{
class DBConnect
{
string strconnection= "Server=localhost;Database=dbname;Trusted_Connection=True;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
We Can Use Following Codes To Do Changes In The Database
1.Insert Data
string query = "INSERT INTO ur_table VALUES('value1','value2')";
DBConnect dbc = new DBConnect();
dbc.connect();
dbc.QryCommand(query);
2.Get Single Data
string query = "SELECT * FROM ur_table";
DBConnect dbc = new DBConnect();
dbc.connect();
DataTable dt = new DataTable();
dt = dbc.ReadData(query);
foreach (DataRow row in dt.Rows)
{
txtName.Text = row[0].ToString();
}
Without Doing Anything Related SQL Stuff In The Current Class We Can Create A Separate Class For That And We Can Handle From Their...
Create A New Class Call DBConnect and Paste The Following Code
This Class Controls All The Sql Related Stuff
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace MyProject
{
class DBConnect
{
string strconnection= "Server=localhost;Database=dbname;Trusted_Connection=True;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
We Can Use Following Codes To Do Changes In The Database
1.Insert Data
string query = "INSERT INTO ur_table VALUES('value1','value2')";
DBConnect dbc = new DBConnect();
dbc.connect();
dbc.QryCommand(query);
2.Get Single Data
string query = "SELECT * FROM ur_table";
DBConnect dbc = new DBConnect();
dbc.connect();
DataTable dt = new DataTable();
dt = dbc.ReadData(query);
foreach (DataRow row in dt.Rows)
{
txtName.Text = row[0].ToString();
}
Jan 6, 2014
Auto Complete ComboBox in C# While Text Changed
This Program Used To Create A Combo Box In C# That Auto Complete With The Suggestions.
I Have Add Following Sample Data To My Combo Box.
Now Type And See,You Will Get Suggestions
If You Want To Add Dynamic Data To Combo Box You Can Do It Inside The Form Load Method.Following Example Load Data To Combo Box From SQL Server Database.
Create A Project and Add A Combo Box To It.
Just Make Sure You Have Change The Following Properties In The Combo Box Properties.
I Have Add Following Sample Data To My Combo Box.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComboBoxSuggest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Apple");
comboBox1.Items.Add("Ball");
comboBox1.Items.Add("Cat");
comboBox1.Items.Add("Dog");
comboBox1.Items.Add("Elephant");
comboBox1.Items.Add("Fish");
comboBox1.Items.Add("Goat");
comboBox1.Items.Add("Animal");
comboBox1.Items.Add("Amazon");
comboBox1.Items.Add("Avatar");
}
}
}
Now Type And See,You Will Get Suggestions
If You Click The Drop down You Can See Everything...
If You Want To Add Dynamic Data To Combo Box You Can Do It Inside The Form Load Method.Following Example Load Data To Combo Box From SQL Server Database.
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComboBoxSuggest
{
public partial class MyForm : Form
{
public Form1()
{
InitializeComponent();
}
private void MyForm_Load(object sender, EventArgs e)
{
loadMyComboBox();
}
private void loadMyComboBox()
{
string query = "SELECT EmpName,Age FROM Employee";
DBConnect dbconnection = new DBConnect();
DataTable datatable = new DataTable();
dbconnection.connect();
datatable = dbconnection.ReadData(query);
dbconnection.connect();
datatable = dbconnection.ReadData(query);
MyComboBox.Items.Clear();//Clearing Existing Items
foreach (DataRow row in dt.Rows)
{
MyComboBox.ItemsAdd(row[0].ToString());
{
MyComboBox.ItemsAdd(row[0].ToString());
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace ComboBoxSuggest
{
class DBConnect
{
string strconnection= "Server=localhost;Database=dbname;Trusted_Connection=True;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace ComboBoxSuggest
{
class DBConnect
{
string strconnection= "Server=localhost;Database=dbname;Trusted_Connection=True;";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public void connect()
{
sqlcon = new SqlConnection(strconnection);
sqlcon.Open();
}
public void disconnect()
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
sqlcon.Dispose();
}
}
public DataTable ReadData(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
return dt;
}
public void QryCommand(string query)
{
try
{
connect();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
disconnect();
}
}
}
}
C# Transfering Data Between Forms
We Have Two Forms For Example..
Form1
Form2
In Form1 You Will Have To Insert A Coding Like This Inside A Event Where Ever You Like It To Be. I Have Choosed It To be Under The Button Click Event.
I Have A Variable In Form1 And Form 2.
Form1 Variable is public string form1variable;
Form2 Variable is public string form2variable;
Now Lets See How To Get Data From Another Form.
private void button1_Click(object sender, EventArgs e)
{
using (Form2 f2 = new Form2())
{
//Below We have To Open Form 2 To Get Them To Form1.
f2.ShowDialog();
{
form1variable = f2.form2variable;
} //When We Close The Form2 We Will Get The Data in form2variable to form1variable.
//Make Sure Data Is Loaded To form2variable.
}
}
------------------------------------------------------------------------------------------------------------
Now Lets See How To Send Data To Another Form.
private void button1_Click(object sender, EventArgs e)
{
using (Form2 f2 = new Form2())
{
f2.form2variable = form1variable;//Setting Form1 variable to Form2
}
}
------------------------------------------------------------------------------------------------------------
Form1
Form2
In Form1 You Will Have To Insert A Coding Like This Inside A Event Where Ever You Like It To Be. I Have Choosed It To be Under The Button Click Event.
I Have A Variable In Form1 And Form 2.
Form1 Variable is public string form1variable;
Form2 Variable is public string form2variable;
Now Lets See How To Get Data From Another Form.
private void button1_Click(object sender, EventArgs e)
{
using (Form2 f2 = new Form2())
{
//Below We have To Open Form 2 To Get Them To Form1.
f2.ShowDialog();
{
form1variable = f2.form2variable;
} //When We Close The Form2 We Will Get The Data in form2variable to form1variable.
//Make Sure Data Is Loaded To form2variable.
}
}
------------------------------------------------------------------------------------------------------------
Now Lets See How To Send Data To Another Form.
private void button1_Click(object sender, EventArgs e)
{
using (Form2 f2 = new Form2())
{
f2.form2variable = form1variable;//Setting Form1 variable to Form2
}
}
------------------------------------------------------------------------------------------------------------
If You Have Any Problem Please Comment Below
HTML Host Webpages on Google Drive
Host webpages on Google Drive
How it works:
- Create a new folder in Drive
- Right Click on that folder then select Share > Share
- Click Change.. which is displayed after [ Private - Only you can access ]
- Click the radio button [ Public on the web ] and Click Save.
- Upload your HTML, JS & CSS files to this folder.
- Right Click on the Html Home Page File of yours > Open With > Google Drive Viewer.
- Then after it opens go to the top left corner where you will find [ Preview ] Next to Zoom IN OUT Icons.And Click It.
- Then after it opens copy the link above in the address bar.
- And pass on to others to view your page..
- Have Fun !!!!.
Any Problems Please Comment Or Mail To . hudhaifa962@gmail.com
Jan 5, 2014
C# Make A TextBox Accept Only 1 (. or ,) with Digits
- You First Have To Go To The Properties Of The Textbox And Find For The Event Keypress And Double Click The Event Then You Will Get A New Event Like Below ..
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
}
- Now All You Have To Copy The Code Below And Paste It Inside The Event Function...
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
----------------------------------------------------------------------------------------------------------------------------------
// only allow one coma
if (e.KeyChar == ',' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
- And It Should Look Like This .. When Done..
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
C# Make A TextBox Accept Only Numeric Values
- You First Have To Go To The Properties Of The Textbox And Find For The Event Keypress And Double Click The Event Then You Will Get A New Event Like Below ..
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
}
- Now All You Have To Copy The Code Below And Paste It Inside The Event Function...
char keypress = e.KeyChar;
if (char.IsDigit(keypress) || e.KeyChar == Convert.ToChar(Keys.Back))
{
//eventChecker("T");
}
else
{
e.Handled = true;
}
- And It Should Look Like This .. When Done..
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
char keypress = e.KeyChar;
if (char.IsDigit(keypress) || e.KeyChar == Convert.ToChar(Keys.Back)){
//eventChecker("T");
}
else
{
e.Handled = true;
}
}
Subscribe to:
Posts (Atom)
JWT Token Decode Using Jquery
When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...
-
In this blog post Ill explain you the logic behind the Sri Lankan National Identity Card (NIC). Sri Lanka now has Old NIC No Format as well ...
-
In This Article I Will Demonstrate You To Create A Simple Chat Program Using Java Remote Method Invocation(RMI). Following Program Supports ...
-
In a windows form application sometimes you may want to import a excel file to a data grid view. In this blog post Ill demonstrate to you gu...