How to show progressbar while sending email using backgroundworker in C#. It should show step by step as we can see while we copy anything to our drive.I am reading excel file to send email.
progressbar1.performstep();
OnClick of Button i am showing Progressbar
private void button2_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
percentageLabel.Visible = true;
backgroundWorker1.RunWorkerAsync();
}
On progress changed event : what to do ??
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progresBar1.PerformStep();
}
On Do work sendmail : (Note : I need backgroundWorker1.ReportProgress should perform step by step, problem is here i knoww but how to do and what to ? please help here)
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(98);
while (!quit)
{
// Code to send email here
sendmail();
}
}
void sendmail()
{
string ConStr = "";
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Program Files\\CreditControl\\CC\\outstanding.xlsx;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
string query = "SELECT [Agent ID] FROM [Sheet1$] group by [Agent ID] ";
OleDbConnection conn = new OleDbConnection(ConStr);
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
System.Data.DataTable dt = new System.Data.DataTable();
da.Fill(dt);
conn.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Agent ID"].ToString() != "")
{
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Program Files\\CreditControl\\CC\\agent_mail_master.xlsx;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
string query2 = "SELECT Mail1,Mail2,Mail3,Mail4,Mail5 FROM [Sheet1$] where [Agent ID] = '" + dt.Rows[i]["Agent ID"].ToString() + "'";
OleDbConnection conn2 = new OleDbConnection(ConStr);
if (conn2.State == ConnectionState.Closed)
{
conn2.Open();
}
OleDbCommand cmd1 = new OleDbCommand(query2, conn2);
OleDbDataAdapter sda = new OleDbDataAdapter(cmd1);
System.Data.DataTable dts = new System.Data.DataTable();
sda.Fill(dts);
conn2.Close();
if (dts.Rows.Count > 0)
{
try
{
SmtpClient SmtpServer = new SmtpClient();
MailMessage mail = new MailMessage();
SmtpServer.Credentials = new System.Net.NetworkCredential("");
SmtpServer.Port = 25;
SmtpServer.Host = "";
mail.From = new MailAddress("");
if (dts.Rows[0]["Mail1"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail1"].ToString());
if (dts.Rows[0]["Mail2"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail2"].ToString());
if (dts.Rows[0]["Mail3"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail3"].ToString());
if (dts.Rows[0]["Mail4"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail4"].ToString());
if (dts.Rows[0]["Mail5"].ToString() != "")
mail.To.Add(dts.Rows[0]["Mail5"].ToString());
mail.Subject = "";
mail.IsBodyHtml = true;
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Program Files\\CreditControl\\CC\\outstanding.xlsx;Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1;\"";
string query3 = "Select [Date],[Agency Name] ,[Agent ID],[Delay Days],[OD Amount],[Receipt Amount],[Outstanding Amount],Remarks,[Entered By] FROM [Sheet1$] where [Agent ID] ='" + dt.Rows[i]["Agent ID"].ToString() + "'";
OleDbConnection conn3 = new OleDbConnection(ConStr);
OleDbCommand cmd2 = new OleDbCommand(query3, conn3);
OleDbDataAdapter oda = new OleDbDataAdapter(cmd2);
System.Data.DataTable dta = new System.Data.DataTable();
oda.Fill(dta);
conn3.Close();
StringBuilder sb = new StringBuilder();
mail.Body = sb.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
quit = true;
}
ON backgroundWorker_RunWorkerCompleted success message :
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
progressBar1.Visible = false;
percentageLabel.Text = "";
MessageBox.Show("Error");
return;
}
else
{
MessageBox.Show("Processed successfully");
System.Windows.Forms.Application.Exit();
}
}
you need to fire the ProgressChangedEvent. something like
bgWorker.ReportProgress( PercentageCompleted(...) );
also be advised that progressBar1.Value expects an Int32 between 0 .. 100 and not a Double between 0 .. 1 (from your code it is not obvious what value you are reporting to your BackgroundWorker)
for ReportStep be sure you set all the required properties. you can find an example on MSDN here
http://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar.performstep(v=vs.110).aspx
so in that case you would need to call pbar1.ReportStep() in your ProressChanged-Method instead of setting the Value of pbar1 directly.
EDIT: this is a very basic example from a derived BackgroundWorker how to deal with these events
public sealed class MyBackgroundWorker : BackgroundWorker
{
public MyBackgroundWorker(ProgressBar pBar)
{
this.MyProgressBar = pBar;
this.WorkerReportsProgress = true;
this.WorkerSupportsCancellation = false;
this.DoWork += MyBackgroundWorker_DoWork;
this.ProgressChanged += MyBackgroundWorker_ProgressChanged;
this.RunWorkerCompleted += MyBackgroundWorker_RunWorkerCompleted;
}
public ProgressBar MyProgressBar { get; private set; }
void MyBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Finish");
}
void MyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
SendMail();
}
void MyBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Boolean either = true; // These are your choices
if (either)
{
// If the ProgressBar has been properly configured regarding
//
// this.myProgressBar.Minimum
// and
// this.myProgressBar.Maximum
//
// you can simply call
this.MyProgressBar.PerformStep();
}
else
{
// If the Progressbar has not been properly configured,
// you have to assign the value provided by
// ProgressChangedEvents e like this
this.MyProgressBar.Value = e.ProgressPercentage;
}
}
private Boolean SendMail()
{
// foreach mail in MailsToSend ...
// Snip - I assume your code for sending mails works correctly
try
{
// Snip
}
catch (Exception ex)
{
// Snip
}
finally
{
this.ReportProgress( (100 * cntMailsSent) / cntTotalMailsToSend);
}
// quit = true; // What do you use this for?
}
}
Related
This is my first time using C# and SQL. I've managed to get the datagridview to work, be it insert, update or delete. However, all the changes that is reflected in the datagridview is NOT updating in the SQL Table (When I open the database and click "Show Table Data", the Insert, Update and Delete changes are not reflected there.)
Please Help! All the videos I've searched up only shows their datagridview changes being reflected, but doesn't show if their SQL Table is actually updated.
My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.InteropServices;
namespace CRUDProj
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displaydata();
button3.Visible = false;
DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
chk.HeaderText = "Select";
chk.ValueType = typeof(bool);
chk.Name = "chkbox";
infoDataGridView.Columns.Insert(0, chk);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cRUDDBDataSet.Info' table. You can move, or remove it, as needed.
this.infoTableAdapter.Fill(this.cRUDDBDataSet.Info);
}
private void infoBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.infoBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.cRUDDBDataSet);
}
private void displaydata()
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Info]";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
DataTable dt = new DataTable();
SqlDataAdapter sdr = new SqlDataAdapter(sqlcomm);
sdr.Fill(dt);
infoDataGridView.DataSource = dt;
sqlconn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "insert into [dbo].[Info] values (#Id, #FullName, #NRIC, #Phone, #Temperature, #LocationLevel, #Date)";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id", iDTextBox.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
MessageBox.Show("Record Successfully Inserted");
displaydata();
sqlconn.Close();
}
public string message = string.Empty;
private void button2_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in infoDataGridView.Rows)
{
bool issellected = Convert.ToBoolean(row.Cells["chkbox"].Value);
if (issellected)
{
message = Environment.NewLine;
message = row.Cells[1].Value.ToString();
}
}
label1.Text = message;
label1.Visible = true;
button3.Visible = true;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
string sqlquery = "update [dbo].[Info] set Id=#Id, FullName=#FullName, NRIC=#NRIC, Phone=#Phone, Temperature=#Temperature, LocationLevel=#LocationLevel, Date=#Date where Id=#Id";
sqlconn.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
sqlcomm.Parameters.AddWithValue("#Id" ,label1.Text);
sqlcomm.Parameters.AddWithValue("#FullName", fullNameTextBox.Text);
sqlcomm.Parameters.AddWithValue("#NRIC", nRICTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Phone", phoneTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Temperature", temperatureTextBox.Text);
sqlcomm.Parameters.AddWithValue("#LocationLevel", locationLevelTextBox.Text);
sqlcomm.Parameters.AddWithValue("#Date", dateTextBox.Text);
sqlcomm.ExecuteNonQuery();
infoTableAdapter.Update(cRUDDBDataSet.Info);
sqlconn.Close();
MessageBox.Show("Record Updated Successfully! ");
displaydata();
button3.Visible = false;
button1.Enabled = true;
button2.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
DataRowView drv = infoDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { drv.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM dbo.Info", sqlconn);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
this.infoTableAdapter.Update(this.cRUDDBDataSet.Info);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button5_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["CRUDProj.Properties.Settings.CRUDDBConnectionString"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(mainconn);
List<String> empselect = new List<String>();
DataGridViewRow row = new DataGridViewRow();
for (int i = 0; i<= infoDataGridView.Rows.Count-1; i++)
{
row = infoDataGridView.Rows[i];
if (Convert.ToBoolean(row.Cells [0].Value)==true)
{
string id = row.Cells[1].Value.ToString();
empselect.Add(id);
}
sqlconn.Open();
foreach (string s in empselect)
{
SqlCommand sqlcomm = new SqlCommand("delete from [dbo].[Info] where Id = ' " + s + " ' ", sqlconn);
sqlcomm.ExecuteNonQuery();
}
sqlconn.Close();
}
MessageBox.Show("Record Deleted Successfully! ");
displaydata();
}
private void iDTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
iDTextBox.Clear();
fullNameTextBox.Clear();
nRICTextBox.Clear();
phoneTextBox.Clear();
temperatureTextBox.Clear();
locationLevelTextBox.Clear();
dateTextBox.Clear();
}
}
}
Bind your DGV to Database this will help you to perform crud operations easily.
This is a sample code on DGV to perform some actions may it will help you. but make sure that you bind your DGV to the database table.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
string _name = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string _lname = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string _sex = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
string _age = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
if (e.ColumnIndex == dataGridView1.Columns["delete"].Index && e.RowIndex >= 0)
{
if(groupBox1.Visible==true)
{
groupBox1.Visible = false;
}
_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
DialogResult result = MessageBox.Show("Do You Want to delete?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
if (result.Equals(DialogResult.OK) && service.deleterecord(_id, _name, _lname, _age, _sex))
{
MessageBox.Show("deleted record");
this.Close();
}
else
{
MessageBox.Show("not deleted");
}
}
if (e.ColumnIndex == dataGridView1.Columns["edit"].Index && e.RowIndex >= 0)
{
groupBox1.Visible = true;
firstname.Text = _name;
lastname.Text = _lname;
gender.Text = _sex;
age.Text = _age;
}
}
private void update_Click(object sender, EventArgs e)
{
string _fname = firstname.Text;
string _lname = lastname.Text;
string _age = age.Text;
string _sex = gender.Text;
try
{
if (string.IsNullOrWhiteSpace(_fname) || string.IsNullOrWhiteSpace(_lname) || string.IsNullOrWhiteSpace(_age) || string.IsNullOrWhiteSpace(_sex) || gender.Equals(null))
{
MessageBox.Show("Please enter the empty fields");
}
else
{
if (Updatedata("Update Query"))
{
MessageBox.Show("Record Updated");
//this.recordTableAdapter.Fill(this.task2DataSet.record);
groupBox1.Visible = false;
this.Size = new Size(595, 258);
this.Close();
}
else
{
MessageBox.Show("Failed to update");
}
}
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
}
}
Below is the code for a Windows Forms application I am using to move data from Excel to a SQL Server database. If I change the server to my local database, it's working and copying 28000 records in 2 seconds.
For another server as mentioned, it keeps running till timeout and sometimes it copies, after a long time.
public partial class form1 : Form
{
public form1()
{
InitializeComponent();
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter= "Excel Files|*.xls;*.xlsx;*.xlsm";
button2.Enabled = false;
lblStatus.Text = null;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string strfilename = openFileDialog1.FileName;
filePath.Text = strfilename;
button2.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
this.Cursor = Cursors.WaitCursor;
lblStatus.Text = "Uploading...";
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 50;
backgroundWorker1.RunWorkerAsync(argument: filePath.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string filePath = (string)e.Argument;
if (File.Exists(filePath))
{
try
{
String Connection = "Data Source=*******; Initial Catalog= ****; User Id=*****; Password= *****; Integrated Security=false;";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (SqlConnection strConnection = new SqlConnection(Connection))
{
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select * from [Sheet0$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection, SqlBulkCopyOptions.TableLock |
SqlBulkCopyOptions.FireTriggers |
SqlBulkCopyOptions.UseInternalTransaction,
null))
{
e.Result = 0;
sqlBulk.DestinationTableName = "tblCMHC";
string sClearSql = "Truncate table " + sqlBulk.DestinationTableName;
SqlConnection sqlConn0 = new SqlConnection(Connection);
SqlCommand sqlCMD0 = new SqlCommand(sClearSql, sqlConn0);
sqlConn0.Open();
sqlCMD0.CommandTimeout = 80000;
sqlCMD0.ExecuteNonQuery();
sqlConn0.Close();
sqlBulk.ColumnMappings.Add("AptSuite", "AptSuite");
sqlBulk.ColumnMappings.Add("City", "City");
sqlBulk.ColumnMappings.Add("ChangedDate", "ChangedDate");
sqlBulk.ColumnMappings.Add("Country", "Country");
sqlBulk.ColumnMappings.Add("Type", "Type");
sqlBulk.ColumnMappings.Add("PostalCode", "PostalCode");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.ColumnMappings.Add("SSN", "SSN");
sqlBulk.ColumnMappings.Add("BirthDate", "BirthDate");
sqlBulk.ColumnMappings.Add("Gender", "Gender");
sqlBulk.ColumnMappings.Add("Race", "Race");
sqlBulk.ColumnMappings.Add("PrimaryLanguage", "PrimaryLanguage");
sqlBulk.ColumnMappings.Add("Education", "Education");
sqlBulk.ColumnMappings.Add("Program", "Program");
sqlBulk.ColumnMappings.Add("PrimaryDx", "PrimaryDx");
sqlBulk.ColumnMappings.Add("PrimaryDxDesc", "PrimaryDxDesc");
sqlBulk.ColumnMappings.Add("SecondaryDx", "SecondaryDx");
sqlBulk.ColumnMappings.Add("SecondaryDxDesc", "SecondaryDxDesc");
sqlBulk.ColumnMappings.Add("AdmissionDate", "AdmissionDate");
sqlBulk.ColumnMappings.Add("DischargeDate", "DischargeDate");
sqlBulk.ColumnMappings.Add("StatusEpisodes", "StatusEpisodes");
sqlBulk.ColumnMappings.Add("StatusClients", "StatusClients");
sqlBulk.ColumnMappings.Add("ClientID", "ClientID");
sqlBulk.ColumnMappings.Add("EffectiveDate", "EffectiveDate");
sqlBulk.BulkCopyTimeout = 1800;
sqlBulk.BatchSize = 3000;
strConnection.Open();
while (dReader.Read())
{
sqlBulk.WriteToServer(dReader);
}
strConnection.Close();
string sCount = "Select count(*) from " + sqlBulk.DestinationTableName;
SqlConnection sqlConn1 = new SqlConnection(Connection);
SqlCommand sqlCMD1 = new SqlCommand(sCount, sqlConn1);
sqlConn1.Open();
sqlCMD1.CommandTimeout = 80000;
int count=(int)sqlCMD1.ExecuteScalar();
sqlConn1.Close();
e.Result = count;
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
MessageBox.Show("File path does not exist");
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.MarqueeAnimationSpeed = 0;
progressBar1.Style = ProgressBarStyle.Blocks;
progressBar1.Value = progressBar1.Minimum;
this.Cursor = Cursors.Default;
lblStatus.Text = null;
int count = (int)e.Result;
MessageBox.Show(count + " Rows Uploaded!");
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
}
I am a beginner in C# and created a database in a Windows Forms App for a customer data, the function of it is to take the user's phone number and then search the table and then if it is found then populate the data fields with the information; otherwise it needs to add the new customer to the table.
When I run the code I get an error
System.ArgumentException: 'Keyword not supported: 'data source(localdb)\mssqlocaldb;attachdbfilename'.'
This is my code:
DataTable TableCust;
SqlConnection cnCust;
SqlDataAdapter dataCust;
DataGrid dtGridCust;
public bool buttonClicked = false;
private static int CurrentOrder = 1000;
private int i = 0;
Validation v = new Validation();
public frmPizzaPetes()
{
InitializeComponent();
}
string dataSource;
string SqlParms;
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}
public bool ifCustIsFound()
{
bool tester=false;
string SqlCustomer = "SELECT*FROM Customers WHERE CustPhone= '" + mtbPhone.Text + "';";
dataCust = new SqlDataAdapter(SqlCustomer, cnCust);
dataCust.Fill(TableCust);
if (TableCust.Rows.Count > 0)
{
txtName.Text = TableCust.Rows[0]["CustName"].ToString();
txtAddress.Text = TableCust.Rows[0]["CustAddress"].ToString();
txtApt.Text = TableCust.Rows[0]["CustSuite"].ToString();
txtCity.Text = TableCust.Rows[0]["CustCity"].ToString();
mtbZip.Text = TableCust.Rows[0]["CustZip"].ToString();
cboState.Text = TableCust.Rows[0]["CustState"].ToString();
// dtGridCust.DataSource = TableCust;
}
else
{
DialogResult dlg=MessageBox.Show("Add Customer?","Customer not found", MessageBoxButtons.YesNo);
if (dlg == DialogResult.Yes)
{
string strConn = dataSource + SqlParms;
SqlDataAdapter adaptSQL = new SqlDataAdapter(strSQL, strConn);
SqlCommand cmdCust = new SqlCommand();
SqlCommandBuilder cmdBld = new SqlCommandBuilder(adaptSQL);
DataRow newCust;
newCust = TableCust.NewRow();
newCust["CustPhone"] = mtbPhone.Text;
newCust["CustName"] = txtName.Text;
newCust["CustAddress1"] = txtAddress.Text;
newCust["CustAddress2"] = txtApt.Text;
newCust["CustCity"] = txtCity.Text;
newCust["CustState"] = cboState.Text;
newCust["CustZip"] = mtbZip.Text;
try
{
TableCust.Rows.Add(newCust);
cmdBld.GetUpdateCommand();
adaptSQL.Update(TableCust);
MessageBox.Show("Customer Added!");
}
catch (SqlException)
{
MessageBox.Show("Customer Add Failed!");
}
}
txtName.Focus();
}
return tester;
}
it seems "=" is missing in data source. Try this.
private void Form1_Load(object sender, EventArgs e)
{
btnAccept.Enabled = false;
lblOrderNo.Text = CurrentOrder.ToString();
Price();
//
dataSource = #"Data Source =(LocalDB)\MSSQLocalDB;AttachDbFilename=|C:\Users\tyada\DATABASE\Pizza.mdf;";
SqlParms = "Integrated Securtiy=True; Connect Timeout==30";
string SqlCust = "select * from Customers";
string strConn = dataSource + SqlParms;
cnCust = new SqlConnection(strConn);
cnCust.Open();
TableCust = new DataTable();
dtGridCust.DataSource = TableCust;
}
After fetching data from database in datagridview last data is repeated but missed the first data in datagridview. I follow this link https://www.mindstick.com/Articles/1148/datagrid-using-backgroundworker-c-sharp
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
RetriveTableData Obj = (RetriveTableData)e.Argument;
string SqlcmdString = "SELECT * from tblBook";
SqlDataReader reader;
int i = 1;
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
Sqlcmd = new SqlCommand(SqlcmdString, conn);
conn.Open();
reader = Sqlcmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//int.Parse(reader["NO_IND"].ToString());
// Obj.EmpId = reader["C_FICH"].ToString();
// Obj.EmpName = reader["C_SITE"].ToString();
Obj.AccessionNo = reader["accessionNo"].ToString();
Obj.Author = reader["author"].ToString();
Thread.Sleep(100);
// To Report progress.
backgroundWorker1.ReportProgress(i, Obj);
if (backgroundWorker1.CancellationPending)
{
// Set the e.Cancel flag so that the WorkerCompleted event
// knows that the process was cancelled.
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
i++;
}
conn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public class RetriveTableData
{
public string AccessionNo;
public string Author;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (!backgroundWorker1.CancellationPending)
{
//Gets the user state that is sent as part of ReportProgress() Method from DoWork Event
RetriveTableData Obj = (RetriveTableData)e.UserState;
//Add the data to the dataGridView1
dataGridView1.Rows.Add(Obj.AccessionNo.ToString(), Obj.Author.ToString());
progressBar1.Value = e.ProgressPercentage;
label1.Text = "Processing row.. " + e.ProgressPercentage.ToString() + " of " + TotalRecords;
}
}
private int GetTotalRecords()
{
SqlConnection con;
SqlCommand cmd;
try
{
using (con = new SqlConnection(connectionString))
{
cmd = new SqlCommand("SELECT COUNT(*) FROM tblBook", con);
con.Open();
TotalRecords = int.Parse(cmd.ExecuteScalar().ToString());
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return TotalRecords;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
label1.Text = "Cancelled by User Intentionally...";
progressBar1.Value = 0;
}
// Check to see if an error occurred in the background process.
else if (e.Error != null)
{
label1.Text = e.Error.Message;
}
else
{
// BackGround Task Completed with out Error
label1.Text = " All Records Loaded...";
}
}
private void button1_Click(object sender, EventArgs e)
{
// statusStrip1.Visible = true;
// toolStripStatusLabel1.Visible = true;
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "Access No.";
dataGridView1.Columns[0].Width = 150;
dataGridView1.Columns[1].Width = 150;
dataGridView1.RowHeadersWidth = 21;
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
dataGridView1.ColumnHeadersHeight = 23;
dataGridView1.Columns[1].Name = "Author";
progressBar1.Maximum = GetTotalRecords();
if (!backgroundWorker1.IsBusy)
{
RetriveTableData TObj = new RetriveTableData();
dataGridView1.Rows.Clear();
// Start the BackGround Thread to Execute
backgroundWorker1.RunWorkerAsync(TObj);
// btStart.Enabled = false;
//btCancel.Enabled = true;
}
}
I got this output where the firstdata: 1122 is missed out and last data PEC-5281 is repeated. Due to my low level i couldnot post image so i put link where you can view the output.
https://krishnas.com.np/2.PNG
You need create a collection of objects for every row nad then use that collection as data source of DataGridView
With async-await it can be done little bid clearer and without extra thread created by BackgroundWorker
private async Task<IEnumerable<RetriveTableData>> GetDataAsync()
{
var query = "SELECT * from tblBook";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
await connection.OpenAsync();
using (var reader = command.ExecuteReaderAsync())
{
var data = new List<RetriveTableData>();
while(await reader.ReadAsync())
{
var temp = new RetriveTableData
{
EmpId = reader["C_FICH"].ToString();
EmpName = reader["C_SITE"].ToString();
AccessionNo = reader["accessionNo"].ToString();
Obj.Author = reader["author"].ToString();
};
data.Add(temp);
}
return data;
}
}
}
Then for example in Form.Load eventhandler you can load data.
private async void Form_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = await GetDataAsync();
}
hello everyone i am using two buttons on same asp.net webpage.both contain different codes
first button fetches the data from database here is the code
protected void Button1_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string checkaddress = "select address,city,zipcode from regforswa where username=" + username;
SqlCommand com = new SqlCommand(checkaddress, conn);
using (var reader = com.ExecuteReader())
{
while (reader.Read())
{
var tmp = reader["address"];
if (tmp != DBNull.Value)
{
laddress.Visible = true;
laddress.Text = reader["address"].ToString();
}
var cty = reader["city"];
if (cty != DBNull.Value)
{
lcity.Visible = true;
lcity.Text = reader["city"].ToString();
}
var zip = reader["zipcode"];
if (zip != DBNull.Value)
{
lzipcode.Visible = true;
lzipcode.Text = reader["zipcode"].ToString();
}
}
}
}
finally
{
conn.Close();
}
}
second button updates the value in the database using textbox values here is the code
protected void submit_Click(object sender, EventArgs e)
{
string username = Request.QueryString["username"];
string address=TextBox4.Text;
string city=TextBox5.Text;
string zipcode=TextBox6.Text;
SqlConnection conn = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=swa1;User Id=swa1;Password=swa1;");
conn.Open();
try
{
string updateaddress = "UPDATE regforswa SET address=#address,city=#city,zipcode=#zipcode WHERE username="+username;
SqlCommand com = new SqlCommand(updateaddress, conn);
com.Parameters.AddWithValue("#address",address);
com.Parameters.AddWithValue("#city",city);
com.Parameters.AddWithValue("#zipcode",zipcode);
// com.Parameters.AddWithValue("#username",username);
if (com.ExecuteNonQuery() == 1)
{
result.Visible = true;
result.Text = "congradulations.your address has been changed";
}
else
{
result.Visible = true;
result.Text = "sorry please try again";
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
but the problem is when i hit the first button the validation controls related to second button does not allow the page to be reloaded so i can not fetch the data.
my question is can we use two buttons on same webpage but with different functionality to perform?
I think you can use "Validation groups" to fix your problem. http://msdn.microsoft.com/en-us/library/ms227424(v=vs.100).aspx