I am trying to show some data in form of report in Windows Form application. I am using ReportViewer in local mode for that purpose. When i run the report, it shows empty report, no errors at all!! Here is my code:
public partial class Form1 : Form
{
String thisConnectionString = "Data Source=AZEEM-NAWAZ;Initial Catalog=IEPL_Attendance_DB;Trusted_Connection = true;";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DataSetProducts.ShowProductByCategory' table. You can move, or remove it, as needed.
//this.ShowProductByCategoryTableAdapter.Fill(this.DataSetProducts.ShowProductByCategory);
//this.reportViewer1.RefreshReport();
//reportViewer1.Visible = false;
SqlConnection thisConnection = new SqlConnection(thisConnectionString);
System.Data.DataSet thisDataSet = new System.Data.DataSet();
string cmdText = "USE [IEPL_Attendance_DB] EXEC [ShowProductByCategory]";
SqlCommand cmd = new SqlCommand(cmdText, thisConnection);
SqlDataAdapter data_ad = new SqlDataAdapter(cmd);
data_ad.Fill(thisDataSet);
/* Associate thisDataSet (now loaded with the stored
procedure result) with the ReportViewer datasource */
ReportDataSource datasource = new ReportDataSource("DataSetProducts_DataSet1", thisDataSet.Tables[0]);
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(datasource);
if (thisDataSet.Tables[0].Rows.Count == 0)
{
MessageBox.Show("Sorry, no products under this category!");
}
reportViewer1.LocalReport.Refresh();
//MessageBox.Show("Total Rows are: " + thisDataSet.Tables[0].Rows[0]["EmployeeName"].ToString());
}
private void reportViewer1_Load(object sender, EventArgs e)
{
}
}
Here are report.rdlc properties:
StoredProcedure "ShowProductByCategory" is returning data and i have verified by displaying rows count via MessageBox!!!
ReportDataSource datasource = new ReportDataSource("DataSetProducts_DataSet1", thisDataSet.Tables[0]);
In the above line remove the "DataSetProducts_" build it and try you will be able to see the data
Related
In my WPF (C#) application I am trying to update my SQL database when changes are made to a datagrid in the app.
Displaying the dataset in the Datagrid works fine, but I can not get updates made in the datagrid sent back to the database.
This is what I have so far - The issue is, that I can't figure out how to pass the dataset (ds) and the sqladapter (sea) to the BtnSave_Click void, which should update the SQL with the changes made (I get a "Mainwindow does not contain a definition for 'ds'). I have been using VB.Net previously and there I could declare them as public variables, but that can't be done here I guess. I have read that I could declare a static class and put them there, but also that that is a bad technique.
I am very thankful for any suggestions on how to proceed. Cheers, Peter.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void grdSchedule_Loaded(object sender, RoutedEventArgs e)
{
string strCon = ConfigurationManager.ConnectionStrings["strCon"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(strCon))
{
CmdString = "SELECT * FROM tbl_Schedule";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.TableMappings.Add("Table", "tbl_Schedule");
DataSet ds = new DataSet("tbl_Schedule");
sda.Fill(ds, "tbl_Schedule");
grdSchedule.ItemsSource =ds.Tables["tbl_Schedule"].DefaultView;
ds.AcceptChanges();
}
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
DataSet changes = this.ds.GetChanges();
if (changes != null)
{
//Data has changes.
//use update method in the adapter. it should update the datasource
int updatedRows = this.sda.Update(changes);
this.ds.AcceptChanges();
}
}
}
}
For save changes via sqlDataAdapter you need to specify commands for properties UpdateCommand, DeleteCommand, InsertCommand.
Also need notice that such commands must contains parameters which will be binded to columns in your DataTable.
var updateCommand = new SqlCommand("Update tbl_schedule set OperationId=#OperationId where Id=#Id")
updateCommand.Parameters.Add("#OperationId", SqlDbType.int, "OperationId")
updateCommand.Parameters.Add("#Id", SqlDbType.Int, "Id");
sda.UpdateCommand = updateComand;
I'm fairly new to C# and coding in general. I've looked through similar questions and didn't have much luck fixing this.
I am making an app that stores Student details for attendance in tables, in a database. Currently when I run it, the details are added to the tables from textboxes. A button opens a separate form with a datagridview, but the details are not updated in this. If I rerun the application and open the second form, the datagridview has been updated. How do I get the datagridview to update based on information added to the table while the application is running?
This is the code that adds the details to the table
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\corry\Desktop\StudentAttendanceBurton\Attendance.mdf;Integrated Security=True";
sc.Open();
using (SqlCommand com = sc.CreateCommand())
{
com.CommandText =
"insert into BUS102(\n" +
" Name,\n" +
" [Student ID],\n" +
" Date)\n" +
"values(\n" +
" #prm_Name,\n" +
" #prm_Student_ID,\n" +
" #prm_Date)";
com.Parameters.Add("#prm_Name", SqlDbType.NVarChar, 50).Value = student.Name;
com.Parameters.Add("#prm_Student_ID", SqlDbType.Int).Value = student.StudentID;
com.Parameters.Add("#prm_Date", SqlDbType.SmallDateTime).Value = student.Date;
com.ExecuteNonQuery();
}
}
This is the code for the form that has the datagridview
public partial class AttendanceForm : Form
{
public AttendanceForm()
{
InitializeComponent();
}
private void bUS102BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.bUS102BindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.attendanceDataSet);
}
private void AttendanceForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'attendanceDataSet.BUS102' table. You can move, or remove it, as needed.
this.bUS102TableAdapter.Fill(this.attendanceDataSet.BUS102);
}
}
public partial class Form1 : Form {
private DataSet m_ds = new DataSet();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
using (SqlConnection conn = new SqlConnection(#"Data Source=YOURSql;Initial Catalog=YOURDB;Integrated Security=True")) {
// set command
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(m_ds);
// bind data to dataGrid
dataGridView1.DataSource = m_ds.Tables[0];
// refresh Data
dataGridView1.Refresh();
conn.Close();
}
}
private void cmdChangeData_Click(object sender, EventArgs e) {
// add new row explicit
DataRow nr = m_ds.Tables[0].NewRow();
nr[0] = "0000";
nr[1] = "xxxx";
// add new row to DataSet (just in memory, NOT TO DB)
m_ds.Tables[0].Rows.Add(nr);
// Refresh Data
dataGridView1.Refresh();
}
}
You have to refresh datagridview
this.dataGridView1.Refresh();
i have a datagridview which loads mysql database table t_pi_clients on form load event,and i have another tab which contains textboxes of the respective columns of t_pi_client, which am able to get data from fullrowselect mode into those textboxes. now i want to update the database upon changes in the those textbox values. so far i've tried some process and gets my "entry saved" messageBox.show but nothing happens to database, so am hoping someone could help me out maybe am missing something thanks
public partial class frmMain : Form
{
MySqlConnection connection;
MySqlDataAdapter mySqlDataAdapter;
DataSet dt = new DataSet();
DataSet DS = new DataSet();
DataSet dg = new DataSet();
public frmMain()
{
InitializeComponent();
}
#region Main load
private void frmMain_Load(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_Clients", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
kryptonDataGridView1.DataSource = DS.Tables[0];
kryptonDataGridView1.Columns[0].Visible = false;
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_msg_charge_Rate", connection);
DataSet dt = new DataSet();
mySqlDataAdapter.Fill(dt);
kryptonDataGridView2.DataSource = dt.Tables[0];
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_client_deposits", connection);
DataSet dg = new DataSet();
mySqlDataAdapter.Fill(dg);
kryptonDataGridView3.DataSource = dg.Tables[0];
}
}
//loads selected row data into textboxes
private void kryptonDataGridView1_DoubleClick(object sender, EventArgs e)
{
textboxClientCode.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientCode"].Value.ToString();
txtboxClientName.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientName"].Value.ToString();
txtboxPostalAddress.Text = kryptonDataGridView1.SelectedRows[0].Cells["PostalAdd"].Value.ToString();
txtboxTelephone.Text = kryptonDataGridView1.SelectedRows[0].Cells["Telephone"].Value.ToString();
txtboxFax.Text = kryptonDataGridView1.SelectedRows[0].Cells["Fax"].Value.ToString();
txtboxEmailAddress1.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd1"].Value.ToString();
txtboxEmailAddress2.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd2"].Value.ToString();
txtboxEmailAddress3.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd3"].Value.ToString();
txtboxWebsite.Text = kryptonDataGridView1.SelectedRows[0].Cells["Website"].Value.ToString();
txtboxChargeRate.Text = kryptonDataGridView1.SelectedRows[0].Cells["ChargeRate"].Value.ToString();
txtboxTotalDepo.Text = kryptonDataGridView1.SelectedRows[0].Cells["TotalDeposit"].Value.ToString();
txtboxAccountBal.Text = kryptonDataGridView1.SelectedRows[0].Cells["AccountBal"].Value.ToString();
txtboxEntrydate.Text = kryptonDataGridView1.SelectedRows[0].Cells["EntryDate"].Value.ToString();
}
now i tried this method to update but doesn't update database
private void kryptonbtnUpdate_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
using (MySqlConnection Conn = new MySqlConnection(connectionString))
if (Conn.State.ToString() != "Open")
{
}
else
{
connection.Open();
}
try
{
DataTable changes = ((DataTable)kryptonDataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)kryptonDataGridView1.DataSource).AcceptChanges();
mySqlDataAdapter.Update(DS);
}
// adapter.Update(rowsToUpdate);
// mySqlDataAdapter.Update(DS);
MessageBox.Show("Entry Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is just a pseudocode of what you need to do
string cmdText = #"UPDATE t_pi_Clients
SET ClientName = #ClientName,
PostalAdd = #PostalAdd,
Telephone = #Telephone,
Fax = #Fax,
.... etc ....
WHERE ClientCode = #ClientCode";
using(MySqlConnection cn = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ClientName", txtboxClientName.Text);
cmd.Parameters.AddWithValue("#PostalAdd", txtboxPostalAddress.Text);
....etc etc...
cmd.Parameters.AddWithValue("#ClientCode", textboxClientCode.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
{
// extract the code that loads DataGridView1 from the Form_Load
// and create a reusable method that you could call from here
}
}
First you build an sql command text with the UPDATE clause. I assume that your primary key (the field that uniquely identifies your records) is the ClientCode field.
Then create the connection and the command. Fill the command parameters collection with the parameters required by your text taking the values from the TextBoxes.
Call the ExecuteNonQuery to store the values.
If you succeed then you need to update or reload your datagridview. The best approach would be setting one by one the gridview cells of the current row with the new values from the textboxes, or you could simply extract the code used in form_load to fill the grid and make a new method that you could call from the button click event. (But this could be slower if you have many records)
I am creating login application (Windows Forms) in C# and using .NET Framework 4.5 with Visual Studio 2012.
I have already entered username and password into database manually.
So in LoginForm, where user enter their username and password my code is like:
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
int MaxRows = 0;
int inc = 0;
private void go_Click(object sender, EventArgs e)
{
DataRow dRow = ds1.Tables["Users"].Rows[inc];
if (EnterMasterPassword.Text == dRow.ItemArray.GetValue(1).ToString())
{
this.DialogResult = DialogResult.OK;
this.Close();
}
else
MessageBox.Show("Try again");
}
private void LoginForm_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\PMDatabase.sdf";
con.Open();
ds1 = new DataSet();
string sql = "SELECT * From tbl_login";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "Users");
MaxRows = ds1.Tables["Users"].Rows.Count;
con.Close();
}
}
*where go is an button*
This works perfectly and users login successfully. But I have no idea how to provide an update/change password functionality to user using Windows Forms. How to update database? And username and password field in it?
So far I have done following procedure:
When user clicks on "Update Password" button a new form (name: Form7) opens which has 3 labels, 3 text-boxes and one button- namely:-
TextBox1--> CurrentPassword
TextBox2--> NewPassword
TextBox3--> ConfirmNewPassword
Button--> UpdateUsrPassword
the code for Form7 is like:-
public partial class Form7 : Form
{
public PasswordsAndData()
{
InitializeComponent();
}
System.Data.SqlServerCe.SqlCeConnection con1;
System.Data.SqlServerCe.SqlCeDataAdapter da1;
DataSet ds2;
int totalPasswords = 0, inc = 0;
private void Form7_Load(object sender, EventArgs e)
{
con1 = new System.Data.SqlServerCe.SqlCeConnection();
con1.ConnectionString = "Data Source=C:\\PMDatabase.sdf";
con1.Open();
ds2 = new DataSet();
string sql = "SELECT * From tbl_UserData";
da1 = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con1);
da1.Fill(ds2, "UserData");
totalPasswords = ds2.Tables["UserData"].Rows.Count;
con1.Close();
}
private void UpdateUsrPassword_Click(object sender, EventArgs e)
{
if(NewPassword.Text == ConfirmNewPassword.Text)
{
DataRow dRow1 = ds2.Tables["UserData"].NewRow();
dRow1[1] = ConfirmNewPassword.Text;
ds2.Tables["UserData"].Rows.Add(dRow1);
UpdateDB();
MessageBox.Show("Password Updated");
totalPasswords++;
inc = totalPasswords - 1;
}
}
private void UpdateDB()
{
System.Data.SqlServerCe.SqlCeCommandBuilder cb1;
cb1 = new System.Data.SqlServerCe.SqlCeCommandBuilder(da1);
cb1.DataAdapter.Update(ds2.Tables["UserData"]);
}
}
But the above code is not updating the password. How to correct above code? So its works perfectly.
Please guide me.
DataRow dRow1 = ds2.Tables["UserData"].NewRow();
dRow1[1] = ConfirmNewPassword.Text;
ds2.Tables["UserData"].Rows.Add(dRow1);
UpdateDB();
You are adding a row in your UpdateUsrPassword_Click but shouldn't you instead updating the existing row?
You should do:
Get actual password from db
UPDATE of the existing row containing the actual password
instead of adding a row you should use something like this:
dataSet1.Tables["Customers"].Rows[4]["CompanyName"] = "Updated Company Name";
this updates the value in the dataset, which you can then push back to the database.
source with more info on editing values in a dataset:
https://msdn.microsoft.com/en-us/library/tat996zc.aspx
I have a form with a read only datagrid view. As the user moves the cursor up and down the datagrid view lines I would like to display a graph that is related to the highlighted line. I tried to use DataGridView1_SelectionChanged event, but it never gets executed.
dataGridView1_CellContentClick_1 does the trick, but requires the user to click which I would like to avoid.
public partial class conf_results : Form
{
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
private NpgsqlDataAdapter da = new NpgsqlDataAdapter();
private NpgsqlCommandBuilder sBuilder = new NpgsqlCommandBuilder();
public conf_results()
{
InitializeComponent();
try
{
// PostgeSQL-style connection string
// Making connection with Npgsql provider
NpgsqlConnection conn;
conn = new NpgsqlConnection(Properties.Settings.Default.connString);
conn.Open();
string sql = "SELECT m.orig_code,m.sejtvonal,round_dbl(m.parm_b,2),round_dbl(m.parm_c,2),round_dbl(m.variance,2),round_dbl(100 /(2^(m.ic50 - 1)),2),m.toxic,m.meres_id, " +
"d.sejtvonal,round_dbl(d.parm_b,2),round_dbl(d.parm_c,2),round_dbl(d.variance,2),round_dbl(100 /(2^(d.ic50 - 1)),2),d.toxic,d.meres_id " +
"from vegyulet_curve m, vegyulet_curve d where m.assay_id=d.assay_id and m.orig_code=d.orig_code "+
"and m.sejtvonal='Mes-Sa' and d.sejtvonal='Dx5'";
da = new NpgsqlDataAdapter(sql, conn);
sBuilder = new NpgsqlCommandBuilder(da);
DataSet ds = new DataSet();
// filling DataSet with result from NpgsqlDataAdapter
//da.Fill(ds);
da.Fill(ds, "vegyulet_curve");
// since it C# DataSet can handle multiple tables, we will select first
dt = ds.Tables["vegyulet_curve"];
// connect grid to DataTable
dataGridView1.DataSource = ds.Tables["vegyulet_curve"];
conn.Close();
}
catch (Exception msg)
{
// something went wrong, and you wanna know why
MessageBox.Show(msg.ToString());
throw;
}
}
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
int i = dataGridView1.SelectedRows[0].Index;;
// I am rewriting the code to use the chart on the form,
// I was debugging, but I could ot get the control
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
//detailForm f = new detailForm(dataGridView1.Rows[e.RowIndex].Cells[11].Value.ToString(),
//dataGridView1.Rows[e.RowIndex].Cells[12].Value.ToString(),
//dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
//this.AddOwnedForm(f);
//f.ShowDialog();
grafikon f = new grafikon(Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString()),
dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(),
Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString()),
Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[14].Value.ToString()),
Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[13].Value.ToString()));
this.AddOwnedForm(f);
f.ShowDialog();
}
}
You can use the event CellMouseEnter to avoid having the user click the cell/row.
But take note, that the event will be invoked for each cell and might cause some performance issue if the user moves the cursor horizontally. What you can do is declare a global variable to hold the current row index, and first check when the event is invoked to see if the row changed or not.