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