Hints:
- The Numbering of Rows Starts from an Index Value of 0 (Zero)
- The Numbering of Columns also starts from an Index Value of 0 (Zero)
- To learn how to Filter the Column Values Please Read Here
- When working with SQL Databases use the System.Data.SqlClient namespace
- Try to create and work with low number of DataTables by simply creating them common for all functions on a form.
- Try NOT to create a DataTable every-time you are working on a new function on the same form because then you will have to carefully dispose it off.
- Try to generate the Connection String dynamically by using the Application.StartupPath.ToString() function so that when the Database is situated on another computer the path referred is correct.
- You can also give a folder or file select dialog box for the user to choose the exact location of the Database which would prove flawless.
- Try instilling Datatype constraints when creating your Database. You can also implement constraints on your forms(like NOT allowing user to enter alphabets in a number field) but this method would provide a double check & would prove flawless to the integrity of the Database.
using System;
using System.Data.SqlClient;
namespace Insert_Show
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+
+ Application.StartupPath.ToString() + "\\Database1.mdf;Integrated Security=True;
User Instance=True");
+ Application.StartupPath.ToString() + "\\Database1.mdf;Integrated Security=True;
User Instance=True");
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Click on Insert Button & then on Show");
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Table1 (fld1, fld2, fld3) VALUES ("
+ "'I '" + "," + "' LOVE '" + "," + "' code-kings.blogspot.com'" + ")", con);
+ "'I '" + "," + "' LOVE '" + "," + "' code-kings.blogspot.com'" + ")", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
private void btnShow_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("Select * from Table1", con);
con.Open();
adp.Fill(table);
MessageBox.Show(table.Rows[0][0] + " " + table.Rows[0][1] + " " +
table.Rows[0][2]);
table.Rows[0][2]);
}
}
}
Please Note :
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** Do not Copy & Paste code written here ; instead type it in your Development Environment
** Testing done in .Net Framework 4.5 but code should be very similar for previous versions of .Net
** All Program Codes written here are 100% tested & running