Friday 10 August 2012

Insert, Update, Delete with DataGridView Control in C# (Windows Application)

DataGridView control is one of the coolest features of Dot Net Framework. You can use this control in Windows Form using Wizard or programmatically.
Add a DataGridView control and two Buttons on a Form. One Button is for deleting the selected row and other one is for updating or inserting new row.
Declare those variables as shown below.



public partial class DataTrialForm : Form
    {
        private String connectionString = null;
        private SqlConnection sqlConnection = null;
        private SqlDataAdapter sqlDataAdapter = null;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private BindingSource bindingSource = null;
        private String selectQueryString = null;

        public DataTrialForm()
        {
            InitializeComponent();
        }

In the Form Load event set data source for the DataGridView control.


private void DataTraiForm_Load(object sender, EventArgs e)
        {
            connectionString = ConfigurationManager.AppSettings["connectionString"];
            sqlConnection = new SqlConnection(connectionString);
            selectQueryString = "SELECT * FROM t_Bill";

            sqlConnection.Open();

            sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

            dataGridViewTrial.DataSource = bindingSource;
            
            // if you want to hide Identity column
            dataGridViewTrial.Columns[0].Visible = false;
        }

To update, insert or delete data in database from DataGridView have a look at this code snippet.


private void addUpadateButton_Click(object sender, EventArgs e)
        {
            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }


        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
               dataGridViewTrial.Rows.RemoveAt(dataGridViewTrial.CurrentRow.Index);
               sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
               MessageBox.Show(exceptionObj.Message.ToString());
            }
        }
 

 More Details :  Live Training jaipur

ComboBox with DataGridView in C#

Using ComboBox with DataGridView is not that complex anymore but it’s almost mandatory while doing some data driven software development.

I have created a DataGridView like this one. Now, I want to show “Month” and “Item” instead of “MonthID” and “ItemID” in DataGridView.



            //Item Data Source

            string selectQueryStringItem= "SELECT ItemID,ItemText FROM Table_Item";

            SqlDataAdapter sqlDataAdapterItem = new SqlDataAdapter(selectQueryStringItem, sqlConnection);
            SqlCommandBuilder sqlCommandBuilderItem = new SqlCommandBuilder(sqlDataAdapterItem);

            DataTable dataTableItem = new DataTable();
            sqlDataAdapterItem.Fill(dataTableItem);
            BindingSource bindingSourceItem = new BindingSource();
            bindingSourceItem.DataSource = dataTableItem;

            //Month Data Source

            string selectQueryStringMonth = "SELECT MonthID,MonthText FROM Table_Month";

            SqlDataAdapter sqlDataAdapterMonth = new SqlDataAdapter(selectQueryStringMonth, sqlConnection);
            SqlCommandBuilder sqlCommandBuilderMonth = new SqlCommandBuilder(sqlDataAdapterMonth);

            DataTable dataTableMonth= new DataTable();
            sqlDataAdapterMonth.Fill(dataTableMonth);
            BindingSource bindingSourceMonth = new BindingSource();
            bindingSourceMonth.DataSource = dataTableMonth;
Let’s start with preparing DataSource for “Item” and “Month” ComboBox.


            //Adding  Month Combo

            DataGridViewComboBoxColumn ColumnMonth = new DataGridViewComboBoxColumn();

            ColumnMonth.DataPropertyName = "MonthID";

            ColumnMonth.HeaderText = "Month";
            ColumnMonth.Width = 120;

            ColumnMonth.DataSource = bindingSourceMonth;
            ColumnMonth.ValueMember = "MonthID";
            ColumnMonth.DisplayMember = "MonthText";

  dataGridViewComboTrial.Columns.Add(ColumnMonth);


            //Adding  Year TextBox

            DataGridViewTextBoxColumn ColumnYear = new DataGridViewTextBoxColumn();
            ColumnYear.HeaderText = "Year";
            ColumnYear.Width = 80;
            ColumnYear.DataPropertyName = "Year";
  
  dataGridViewComboTrial.Columns.Add(ColumnYear);
Set the “DataSource” and most importantly set the “DataPropertyName” accurately for “ColumnMonth” .


            //Adding  Item ComboBox

            DataGridViewComboBoxColumn ColumnItem = new DataGridViewComboBoxColumn();
            ColumnItem.DataPropertyName = "ItemID";
            ColumnItem.HeaderText = "Item";
            ColumnItem.Width = 120;

            ColumnItem.DataSource = bindingSourceItem;
            ColumnItem.ValueMember = "ItemID";
            ColumnItem.DisplayMember = "ItemText";

            dataGridViewComboTrial.Columns.Add(ColumnItem);

            //Adding  Year TextBox

            DataGridViewTextBoxColumn ColumnSaleAmount = new DataGridViewTextBoxColumn();
            ColumnSaleAmount.HeaderText = "Total Sale";
            ColumnSaleAmount.Width = 120;
            ColumnSaleAmount.DataPropertyName = "SaleAmount";

            dataGridViewComboTrial.Columns.Add(ColumnSaleAmount);

            //Adding  Remarks TextBox

            DataGridViewTextBoxColumn ColumnSaleRemarks = new DataGridViewTextBoxColumn();
            ColumnSaleRemarks.HeaderText = "Remarks";
            ColumnSaleRemarks.Width = 150;
            ColumnSaleRemarks.DataPropertyName = "Remarks";

            dataGridViewComboTrial.Columns.Add(ColumnSaleRemarks);


Set the “DataSource” and “DataPropertyName” for “ColumnItem” .


     public partial class DataGridViewComboForm : Form
     {
        private String connectionString = null;
        private SqlConnection sqlConnection = null;
        private SqlDataAdapter sqlDataAdapter = null;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private BindingSource bindingSource = null;
        private String selectQueryString = null;

        public DataGridViewComboForm()
        {
            InitializeComponent();
        }

        private void DataGridViewComboForm_Load(object sender, EventArgs e)
        {
            connectionString = ConfigurationManager.AppSettings["connectionString"];
            sqlConnection = new SqlConnection(connectionString);
            sqlConnection.Open();

            //DataGridView Source

            selectQueryString = "SELECT * FROM Table_SaleSummary";
                        
            sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

Prepare DataSource For your DataGridView.


            //Setting Data Source for DataGridView

            dataGridViewComboTrial.DataSource = bindingSource;

Finally, set DataSource for the DataGridView and get your expected output the following one.



        private void addUpadateButton_Click(object sender, EventArgs e)
        {
            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridViewComboTrial.Rows.RemoveAt(dataGridViewComboTrial.CurrentRow.Index);
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }

        }

 More Details :  Live Training jaipur


sending email in c#

Following self explanatory code snippets will demonstrate how to use .Net Mail to send Mail in C#. First of all, add “Using Directive” to .Net Mail and .Net Mime. The later one is for Mail attachment.

using System.Net.Mail;
using System.Net.Mime;
Let's start with SmtpClient. Here, I have created SmtpClient Object using my Gmail Account.

SmtpClient smtpServer = new SmtpClient();

smtpServer.Credentials = new System.Net.NetworkCredential("khan.rahim@gmail.com", "xxxxxx");
smtpServer.Port = 587;
smtpServer.Host = "smtp.gmail.com";
smtpServer.EnableSsl = true;
This following code snippet shows how to prepare your MailMessage.

MailMessage mailMessage = new MailMessage();

mailMessage.From = new MailAddress("khan.rahim@gmail.com", "A Rahim Khan", System.Text.Encoding.UTF8);
mailMessage.To.Add("rahim767@yahoo.com");

mailMessage.Subject = "Mail Using C# Code";
mailMessage.Body = "I have Used .Net Mail to send this Mail";

mailMessage.Attachments.Add(new Attachment("FILE PATH");

mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mailMessage.ReplyTo = new MailAddress("khan.rahim@gmail.com");

Finally, send your MailMessage by SmtpClient in this way.

smtpServer.Send(mailMessage);
 

 More Details :  Live Training in jaipur

 

How to set Crystal Report Header in Visual Studio 2008

string amount = amountTextBox.Text;
string titleString = "        Total Sanctions above  ";

List investmentList = new List();
investmentList = new InvestmentManager().CollectAmountWiseInvestment(amount);

expirySanctionCrystalReport reportDocumentObject = new expirySanctionCrystalReport();

//Set Crystal Report Header 
CrystalDecisions.CrystalReports.Engine.TextObject amountText = (CrystalDecisions.CrystalReports.Engine.TextObject)reportDocumentObject.ReportDefinition.ReportObjects["dateText"];
amountText.Text = amount;

CrystalDecisions.CrystalReports.Engine.TextObject titleText = (CrystalDecisions.CrystalReports.Engine.TextObject)reportDocumentObject.ReportDefinition.ReportObjects["TextTitle"];
titleText.Text = titleString;

reportDocumentObject.SetDataSource(investmentList);
amountWiseCrystalReportViewer.ReportSource = reportDocumentObject;
amountWiseCrystalReportViewer.RefreshReport();
amountWiseCrystalReportViewer.Visible = true;
 

 More Details :  Live Training in jaipur

 

Number Only TextBox C# Windows Application

private void numberOnlyTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
 //allow digits only
 if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
 {
   e.Handled = true;
 }

 // allow one decimal point
 if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
 {
  e.Handled = true;
 }
}
 

 More Details :  Live Training in jaipur

 

ASP.NET File Upload and Download

ASP.NET File Uploader is an easy to use control. Just drag and drop the control on your page and write this code snippet at Button Click Event to upload the file.

if (studentFileUpload.HasFile == true)
{
  string filename = Path.GetFileName(studentFileUpload.FileName);
  studentFileUpload.SaveAs(Server.MapPath("~/DataFile/") + filename);
}

To download file use this code snippet Link Button or Button Click event.

protected void DownloadLinkButton_Click(object sender, EventArgs e)
{
   string fileName = fileNameLabel.Text;
   string filePath = Server.MapPath("~/DataFile/" + fileName + ".txt"); 
   HttpContext.Current.Response.ContentType =  "application/octet-stream";
   HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" +     System.IO.Path.GetFileName(filePath));
   HttpContext.Current.Response.Clear();
   HttpContext.Current.Response.WriteFile(filePath);
   HttpContext.Current.Response.End();
}
 

Industrial Training in jaipur for MCA or btech student : Chipsoul Web Solution

 

How to delete files from a specific folder using datetime constraint (C# code)

To delete files from a specific folder you can use following code snippet written in c#.

foreach (FileInfo fileInformation in new DirectoryInfo(@”I:/TrialTesting/”).GetFiles())
{
  File.Delete(fileInformation.FullName);                        
}
However, you can delete files comparing “Date Modeified ” attribute . Have a look at the following code snippet. This will delete all files from folder except last five day’s files.

try
{
 DateTime systemDate = DateTime.Now;
 int DefaultDay = 5;
 foreach (FileInfo fileInformation in new DirectoryInfo(@”I:/TrialTesting/”).GetFiles())
 {
   TimeSpan difference;
   difference = systemDate - fileInformation.LastWriteTime;
   //Delete Files from Folder
   if (difference.Days >= DefaultDay)
   {
     File.Delete(fileInformation.FullName);
   }
 }                   
}
catch (Exception ex)
{
 MessageBox.Show(ex.Message.ToString());
}

 More Details :  Live Training in jaipur

 

Insert, Update, Delete with DataGridView Control in C# (Windows Application)

DataGridView control is one of the coolest features of Dot Net Framework. You can use this control in Windows Form using Wizard or programmatically.
Add a DataGridView control and two Buttons on a Form. One Button is for deleting the selected row and other one is for updating or inserting new row.
Declare those variables as shown below.



public partial class DataTrialForm : Form
    {
        private String connectionString = null;
        private SqlConnection sqlConnection = null;
        private SqlDataAdapter sqlDataAdapter = null;
        private SqlCommandBuilder sqlCommandBuilder = null;
        private DataTable dataTable = null;
        private BindingSource bindingSource = null;
        private String selectQueryString = null;

        public DataTrialForm()
        {
            InitializeComponent();
        }

In the Form Load event set data source for the DataGridView control.


private void DataTraiForm_Load(object sender, EventArgs e)
        {
            connectionString = ConfigurationManager.AppSettings["connectionString"];
            sqlConnection = new SqlConnection(connectionString);
            selectQueryString = "SELECT * FROM t_Bill";

            sqlConnection.Open();

            sqlDataAdapter = new SqlDataAdapter(selectQueryString, sqlConnection);
            sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);

            dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);
            bindingSource = new BindingSource();
            bindingSource.DataSource = dataTable;

            dataGridViewTrial.DataSource = bindingSource;
            
            // if you want to hide Identity column
            dataGridViewTrial.Columns[0].Visible = false;
        }

To update, insert or delete data in database from DataGridView have a look at this code snippet.


private void addUpadateButton_Click(object sender, EventArgs e)
        {
            try
            {
                sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
                MessageBox.Show(exceptionObj.Message.ToString());
            }
        }


        private void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
               dataGridViewTrial.Rows.RemoveAt(dataGridViewTrial.CurrentRow.Index);
               sqlDataAdapter.Update(dataTable);
            }
            catch (Exception exceptionObj)
            {
               MessageBox.Show(exceptionObj.Message.ToString());
            }
        }

 More Details :  Live Training jaipur

 

How to convert DataTable to XML in C#

Method for convert DataTable to XML in C#



 public string ConvertToXML(DataTable dt)
{
MemoryStream mstr = new MemoryStream();
dt.WriteXml(mstr, true);
mstr.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(mstr);
string xmlString;
xmlString = sr.ReadToEnd();
return (xmlString);
}
OR
///
/// This method is used to convert the DataTable into string XML format.
///
/// DataTable to be converted./// (string) XML form of the DataTable.
private static string ConvertDataTableToXML(DataTable dtBuildSQL)
{
DataSet dsBuildSQL = new DataSet();
StringBuilder sbSQL;
StringWriter swSQL;
string XMLformat;
sbSQL = new StringBuilder();
swSQL = new StringWriter(sbSQL);
dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
dsBuildSQL.Tables[0].TableName = "Table";
foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
{
col.ColumnMapping = MappingType.Attribute;
}
dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
XMLformat = sbSQL.ToString();
return XMLformat;
}

More Details : Live Training in jaipur

Method for Download a document file from datatable using c#.net

The following  method is for download a document file from datatable .I am taking a column name as Document.


Write this method in any pageload (or) in any button click event:



     private void download(DataTable dt)
     {
        Byte[] bytes = (Byte[])dt.Rows[0]["Document"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = dt.Rows[0]["DocumentType"].ToString();
        Response.AddHeader("content-disposition", "attachment;filename="
        + dt.Rows[0]["NameOfDocument"].ToString());
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }

bind datagridview in c#

Bind data to Datagridview in window application is same as bind data to Gridview in web application.
First Create one windows forms application give the name as Form.cs. In that form drag Datagridview from toolbox  and double click on form then form_load event will be opend in that write the following code:
private void Form1_Load(object sender, EventArgs e)
        {
            //This connection string is used to connect to database
            String strConnection = "Data Source=naresh;Initial Catalog=EMPDB;Integrated Security=True";
            //Establish SQL Connection
            SqlConnection con = new SqlConnection(strConnection);
            //Open database connection to connect to SQL Server
            con.Open();
            //Data table is used to bind the resultant data
            DataSet dsempdetails = new DataSet ();
            // Create a new data adapter based on the specified query.
            SqlDataAdapter da = new SqlDataAdapter("Select * from UserMaster", con);
            //SQl command builder is used to get data from database based on query
            SqlCommandBuilder cmd = new SqlCommandBuilder(da);
            //Fill data table
            da.Fill(dsempdetails,"EmpTable");
            //assigning data table to Datagridview
            dataGridView1.DataSource = dsempdetails .Tables[0];
            //Resize the Datagridview column to fit the gridview columns with data in datagridview
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            con.Close();
        }
After bind data to DataGridView then the output will be shown like this:

jave script key code

When we use keyboard keys in your JavaScript function then the following codes will be useful to write condition statement in your function.
For Example:
We have one textbox and button for login for that you type your username in textbox then instead of clicking Login button if you click on enter key in your keyboard then it has to be login.
For  that the following function will work in onkeypress event.
The enter key value is 13.
<input type="text" id="txtSearch" onkeypress="searchKeyPress(event);" />
    <input type="button" id="btnSearch" Value="Search" onclick="anyfunction();" />

    <script>
    function searchKeyPress(e)
    {
        if (typeof e == 'undefined' && window.event) { e = window.event; }
        if (e.keyCode == 13)
        {
            document.getElementById('btnSearch').click();
        }
    }
    </script>
The following are Java script   Key Codes for Keyboard Characters :
backspace
8
tab
9
 enter
13
shift
16
ctrl
17
alt
18
pause/break
19
caps lock
20
escape
27
page up
33
page down
34
end
35
home
36
left arrow
37
up arrow
38
right arrow
39
down arrow
40
insert
45
delete
46
0
48
1
49
2
50
3
51
4
52
5
53
6
54
7
55
8
56
9
57
a
65
b
66
c
67
d
68
      e
     69
      f
     70
      g
     71
      h 
     72
      i
     73
      j 
     74
      k
     75
      l 
     76
      m
     77
      n
     78
      o 
     79
      p
     80
      q
     81
      r
     82
      s
     83
     T
     84
     U
     85
     V
     86
     W
     87
     X
     88
     y
     89
     z
     90
  Left window key
     91
  Right window key
     92
  Select key
     93
  numpad 0
     96
  numpad 1
     97
  numpad 2
     98
  numpad 3
     99
  numpad 4
    100
  numpad 5 
    101
  numpad 6
    102
  numpad 7
    103
  numpad 8 
    104
  numpad 9
    105
  multiply
    106
  add
    107
  subtract
    109
  decimal point
    110
  divide
    111
  f1
    112
  f2
    113
  f3
    114
  f4
    115
  f5
    116
  f6
    117
  f7
    118
  f8
    119
  f9
    120
  f10
    121
  f11
    122
  f12 
    123
  num lock
    144
  scroll lock
    145
  semi-colon
    186
  equal sign
    187
  comma
    188
  dash
    189
  period
    190
  forward slash
    191
  grave accent 
    192
  open bracket
    219
  back slash
    220
  close braket
    221
  single quote
    222