SQL insert command only working once in a loop - c#

This is s for loop and it will go to the times and will put the time column as true. This works for the first time, but when the time increases by 0.5, it stays false. The for loop is working as i tried a MessageBox.Show("" + Time1 + ""); inside the for loop.
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command = new SqlCommand("INSERT INTO Slots ([Date],[RoomID],[" + Time1 + "]) Values (#date,#room,1)", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Here is what the database looks like, the first true field works, but when it loops to another time, it remains false, I think it may be due to the fact that if I have an existing row with that date (date is primary key), i cannot update that row, so i might need to have an IF the row exists, update, else create a new row.

Try this, you don't have to open connection in each loop, create your sql statement first looping through each value and then do insert using one statement
private string CreateInsertStatement(double time_began_5, double time_finished_5)
{
string sql = "INSERT INTO Slots ([Date],[RoomID],";
string valuesql = " Values (#date,#room,";
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
sql+ = "[" + Time1 + "],";
valuesql+ = "1,";
}
sql = sql.TrimEnd(',') + ") ";
valuesql = valuesql.TrimEnd(',') + ") ";
return sql + valuesql;
}
private string CreateUpdateStatement(double time_began_5, double time_finished_5)
{
string sql = "UPDATE Slots SET ";
string wheresql = " WHERE [Date] = #date AND [RoomID] = #room";
for (double Time = time_began_5; Time < time_finished_5; Time = Time + 0.5)
{
string Time1 = Time.ToString("0.00");
sql+ = "[" + Time1 + "] = 1,";
}
sql = sql.TrimEnd(',');
return sql + wheresql;
}
Then in you actual insert code:
try
{
SqlConnection cn = new SqlConnection("Data Source=.\\SqlExpress;Initial Catalog=AllensCroft;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework;");
cn.Open();
SqlCommand Command;
//check if row exists
Command = new SqlCommand("select count(*) from Slots WHERE [Date] = #date AND [RoomID] = #room", cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
var cnt = Command.ExecuteScalar();
if(cnt!=null)
{
string sqlstr = ""
if(Int32.Parse(cnt.ToString()) > 0)
{
sqlstr = CreateUpdateStatement(time_began_5,time_finished_5);
}
else if(Int32.Parse(cnt.ToString()) == 0)
{
sqlstr = CreateInsertStatement(time_began_5,time_finished_5);
}
Command = new SqlCommand(sqlstr, cn);
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
}
try
{
cn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

You are doing an insert.
In every loop you insert a new row and set the value true only for the column which name is equal to the current value of the variable Time1.
Not having a value for the other columns they probably default to false. (bit columns I suppose)
If you want a default to true for every column perhaps it is better to change the database schema adding the default for every time column, otherwise you need a long list of parameters
EDIT: If your logic dictates that you need only one row per date and set every time column to true if you enter the situation above then you can move this logic in the database using a stored procedure:
CREATE PROCEDURE InsertOrUpdateSlotFromCode(#dt smalldatetime, #roomID int)
AS
BEGIN
DECLARE #cnt INT
SELECT #cnt = COUNT(*) from Slots WHERE [Date] = #dt
if #cnt = 0
INSERT INTO Slots ([Date],[RoomID], <here all the time fields> VALUES (#dt, #roomID, 1, ....)
else
UPDATE Slots SET [09.00] = 1, ..... WHERE [Date] = #dt
End
END
then your code call the sp
using(SqlConnection cn = new SqlConnection(.........))
{
cn.Open();
SqlCommand Command = new SqlCommand("InsertOrUpdateSlotFromCode", cn);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("date", date);
Command.Parameters.AddWithValue("room", rooms_combo.SelectedValue);
Command.ExecuteNonQuery();
}
Of course now you can completely get rid of the loop

Related

Compare Two Date From Date at Form C# Visual Studio and Date From Database SQL Server

I want make a auto number based date and number at "Transaction" Form. But i have problem with make a "condition" to compare date "today" and date "yesterday". If date is different, then will make a new "autonumber" from number 1. For example, that date is 2019-08-08 so the ID from "permintaanId" is P2019080803 (two last number is how many transaction make that day). And tomorrow is 2019-08-09 will make ID P2019080901 (two last number will reset because no one transaction make)
private void auto()
{
long hitung;
string urut;
SqlConnection conn = konn.GetConn();
conn.Open();
cmd = new SqlCommand("select permintaanId from permintaan_data where permintaanId in(select max(permintaanId) from permintaan_data) order by permintaanId DESC", conn);
rd = cmd.ExecuteReader();
rd.Read();
if (rd.HasRows) //<- this condition
{
hitung = Convert.ToInt64(rd[0].ToString().Substring(rd["permintaanId"].ToString().Length - 2, 2)) + 1;
string joinstr = "00" + hitung;
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + joinstr.Substring(joinstr.Length - 2, 2);
}
else
{
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + "01";
}
rd.Close();
txt_noPermintaan.Text = urut;
conn.Close();
}
get last item created
cmd = new SqlCommand("select top1 permintaanId from permintaan_data order by DESC", conn);
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
var id = rd["the one with p and 2 numbers at the end"].ToString();
var dateLastCreated = id.ToString().Remove(0,1).Remove(id.Length-2,2);
if (dateLastCreated == DateTime.Now.ToString("yyyyMMdd"))
{
//increment
}
else
{
//create new
}
}
DECLARE #permintaanId INT=0
DECLARE #NewNo VARCHAR(40)=''
select #permintaanId=CAST(ISNULL(MAX(RIGHT(permintaanId,1)),0)+1 AS INT)
FROM permintaan_data
WHERE CAST([tranData] AS DATE) =CAST(GETDATE() AS DATE)
SET #NewNo='P'+CONVERT(VARCHAR(10),GETDATE(),112)+CAST(#permintaanId AS VARCHAR(10))
SELECT #NewNo

How to execute INSERT INTO in SQLite with ODBC in c#

The function of application is to select some values from one database (PSQL) and insert it into another database (SQLite). But code below does not work, it stops at executing line and shows no error, but last forever (also if I use SELECT TOP 1 ...).
//... odbc conection to DSN, this works fine
odbc.dbsqlite.Open();
odbc.dbpsql.Open();
//sql command
OdbcCommand comsqlite = odbc.dbsqlite.CreateCommand();
OdbcCommand compsql = odbc.dbpsql.CreateCommand();
//SQL for select ... this works
compsql.CommandText = "SELECT DISTINCT ..."
compsql.Parameters.AddWithValue("#sifra", "VP");
...
// from here is problem
try
{
OdbcDataReader dbReader = compsql.ExecuteReader();
OdbcTransaction transaction = odbc.dbsqlite.BeginTransaction();
var ordinal = new
{
cenik = dbReader.GetOrdinal("sifra"),
ident = dbReader.GetOrdinal("ident"),
klasi = dbReader.GetOrdinal("klasi"),
cena = dbReader.GetOrdinal("cena"),
eankoda = dbReader.GetOrdinal("eankoda"),
};
int count = 0;
while (dbReader.Read())
{
//here single variable gets results
var cena = Convert.ToDouble(dbReader.GetDouble(ordinal.cena));
var ident = Convert.ToString(dbReader.GetString(ordinal.ident));
var cenik = Convert.ToString(dbReader.GetString(ordinal.cenik));
var klasi = Convert.ToString(dbReader.GetString(ordinal.klasi));
var eanko = Convert.ToString(dbReader.GetString(ordinal.eankoda));
comsqlite.CommandText = "INSERT INTO ARTIKLI (KLASI, CENA, BARKODA, CENIK, IDENT) VALUES (?,?,?,?,?);";
comsqlite.Parameters.AddWithValue("#KLASI", klasi);
comsqlite.Parameters.AddWithValue("#CENA", cena);
comsqlite.Parameters.AddWithValue("#BARKODA", eanko);
comsqlite.Parameters.AddWithValue("#CENIK", cenik);
comsqlite.Parameters.AddWithValue("#IDENT", ident);
if (count % 1000 == 0)
{
transaction.Commit();
transaction.Dispose();
**comsqlite.ExecuteNonQuery(); //here it stops and give no results**
transaction = odbc.dbsqlite.BeginTransaction();
}
count++;
}
comsqlite.Dispose();
odbc.dbsqlite.Close();
transaction.Commit();
transaction.Dispose();
dbReader.Close();
compsql.Dispose();
odbc.dbpsql.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: "+ e);
throw;
}
I am not sure what your CommandText looks like at this point, but you should try to set some single quotation marks around the values being strings/characters in your database.
comsqlite.CommandText = "INSERT INTO ARTIKLI (KLASI, CENA, BARKODA, CENIK, IDENT) VALUES ('?','?','?','?','?');";

Auto generate and AutoIncrement ID in C# when trying to add new record to database

I'm using this code to select the maxID from a database table and each time I want to add a new record, the autogenerated ID is not the last one +1.
public formularAddCompanie()
{
InitializeComponent();
try
{
string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=TrafficManager;Integrated Security=True";
string select = "SELECT max(IDCompanie) FROM Companii";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd2 = new SqlCommand(select, con);
SqlDataReader sda = cmd2.ExecuteReader();
DataTable idmax = new DataTable("idmax");
idmax.Load(sda);
if (idmax.Rows[0][0].ToString().Trim() == "") { txtID.Text = "1"; }
else { txtID.Text = (int.Parse(idmax.Rows[0][0] .ToString() + 1).ToString()); }
}
}
catch (Exception er) { MessageBox.Show(er.Message); }
}
The table from where the selection is made, looks like this:
IDCompany Name Address City RegNo
1 A Street NY 123
Each time I want to add a new record, the autogenerated ID is like this: 11, 111, 1111. It takes the last ID and add another 1 next to it. What am I missing?
Interestingly, note that
string a = "The meaning of life is " + 42;
converts 42 to a string, creating the result
a == "The meaning of life is 42"
Look at this code:
(int.Parse(idmax.Rows[0][0] .ToString() + 1).ToString()); }
You are converting idmax.Rows[0][0] to a string and adding +1 to the end of the string rather than to an integer value. Try
(int.Parse(idmax.Rows[0][0].ToString()) + 1).ToString(); }
Note that idmax.Rows[0][0] should already have an integer in it (as pointed out in the comments). If that's the case, you can simplify to
(idmax.Rows[0][0] + 1).ToString(); }
idmax.Rows[0][0].ToString() + 1 produces string, not int.
You can try
txtID.Text = (Convert.ToInt32(idmax.Rows[0][0]) + 1).ToString();
I just add this because it seems that none cares about the weakness of the code posted by the poster.
First the MAX function is not reliable if you want to find the next autoincrement value that will be assigned to an ID column. Concurrency could wreak havoc with any schema that use MAX. Just suppose that another user has already retrieved the MAX for its own INSERT operation, then depending on the relative speed of the two computers you or the other user will insert a duplicate value for the IDCompany field.
The only correct way to do this common task is to use the IDENTITY property for the column IDCompany and when you need to insert a new record you should write something like this
try
{
string insert = "INSERT INTO Companii (Name,Address,City,RegNo)
VALUES(#name,#address,#city,#regno);
SELECT SCOPE_IDENTITY()";
using (SqlConnection con = new SqlConnection(cs))
using (SqlCommand cmd = new SqlCommand(insert, con))
{
con.Open();
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = txtBoxCity.Text;
.... and on for the other parameters ....
int companyID = Convert.ToInt32(cmd.ExecuteScalar());
... work with the just added company if required
}
}
catch (Exception er)
{ MessageBox.Show(er.Message); }
SCOPE_IDENTITY will return the last identity value inserted into an identity column in the same scope and in this context scope means the connection used by your command.
In any case, if the MAX approach is still required then the code could be simplified a lot using a modified query and SqlCommand.ExecuteScalar instead of building an SqlDataReader, filling a datatable, trying to parse the result with ifs
string getMax = #"select COALESCE(MAX(IDCompany), 0) + 1 AS maxPlusOne
from Companii"
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(getMax, cnn))
{
cnn.Open();
int nextCompanyID = Convert.ToInt32(cmd.ExecuteScalar());
}
The COALESCE function checks the result of the MAX function and if it is NULL returns the second parameter (here 0), then just increment by 1 to get the next MAX directly from the database. ExecuteScalar will do the call returning just the maxPlusOne alias field
try this snippet:
Convert Your String into Int. String with + operator will con-cat and with int it will add numbers.
if (idmax.Rows[0][0].ToString().Trim() == "") { txtID.Text = "1"; }
else {
txtID.Text = Convert.ToString(Convert.ToInt32(idmax.Rows[0][0] .ToString())+1); }
Try This one, my id format is USR001.The code will generate auto id based on the last id inside the database. If the last id in the database is USR001, the the code will generate USR002 and put the id to the textbox
con.Open();
string sqlQuery = "SELECT TOP 1 kode_user from USERADM order by kode_user desc";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string input = dr["kode_user"].ToString();
string angka = input.Substring(input.Length - Math.Min(3, input.Length));
int number = Convert.ToInt32(angka);
number += 1;
string str = number.ToString("D3");
txtKodeUser.Text = "USR" + str;
}
con.Close();

How to add 'loanPaid' every month

I'm facing a problem where every time I refresh my page, the loan paid will increase by 500. I understand that my logic is wrong, after 1 month from the loan application date, the 'loanPaid' will increase by 500 but what I want to happen is every next month it will increase by $500. If anyone who can help me with the logic. I would appreciate it. I was thinking of using some loop but not sure which one and how. I'm a freshman student only so please pardon my coding style. Thank you
public class LoanDAL
{
string connString = ConfigurationManager.ConnectionStrings["Oakhorizons"].ToString();
public LoanDAL()
{
//
// TODO: Add constructor logic here
//
}
public DataTable getAllLoanInfoDT()
{
using (SqlConnection conn = new SqlConnection(connString))
{
DataTable dt = new DataTable();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn;
// cmd.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "SELECT DISTINCT purchaseDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
cmd2.Parameters.AddWithValue("#custID", "OH00002");
cmd2.Parameters.AddWithValue("#loanType", "Personal Loan");
conn.Open();
string custID = "OH00002";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd2;
da.Fill(dt);
int iMonthNo = int.Parse(System.DateTime.Now.Month.ToString());
DateTime dtDate = new DateTime(2000, iMonthNo, 1);
double dMonthNow = Double.Parse(dtDate.ToString("MM"));
LoanTableAdapters.LoanPortfolioTableAdapter loanAdapter = new LoanPortfolioTableAdapter();
string LoanDate = loanAdapter.RetrieveData(custID.ToString()).ToString();
string month = dt.ToString();
double dLoanDate = Double.Parse(LoanDate.Substring(3, 2));
if (dMonthNow > dLoanDate)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + 500";
sql += "WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
cmd2.Connection = conn;
cmd2.CommandText = sql;
cmd2.ExecuteNonQuery();
}
conn.Close();
}
}
After edit:
public DataTable getAllLoanInfoDT()
{
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn;
// cmd.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "SELECT DISTINCT loanUpdateDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
cmd2.Parameters.AddWithValue("#custID", "OH00002");
cmd2.Parameters.AddWithValue("#loanType", "Personal Loan");
conn.Open();
SqlDataReader myReader = cmd2.ExecuteReader();
DateTime loanUpdateDate = Convert.ToDateTime(myReader);
DateTime currDateTime = DateTime.Now;
int loanToBeAdded = (((currDateTime.Year - loanUpdateDate.Year) * 12) + currDateTime.Month - loanUpdateDate.Month) * 500;
if (loanToBeAdded > 0)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", loanUpdateDate = " + DateTime.Now.ToString();
sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
//Execute the above query here
}
conn.Close();
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
return dTable;
}
}
}
You have done a lot of unnecessary things, some important checks missing and some performance inhibiting mistakes also in your code but I will not point them out here since you are a freshman and you will learn gradually.
The solution to your problem should be the following
Firstly create a new column in your "LoanPortfolio" table namely "LastUpdatedLoanPaidDate". The type should be Date for this column. This will store the date when you last added $500 to "loanPaid" column.
Set this column same as "purchaseDate" when you first add a row in your "LoanPortfolio" table. So initially "purchaseDate" and "LastUpdatedLoanPaidDate" will be same.
Fetch only "LastUpdatedLoanPaidDate" instead of "purchaseDate" as
cmd2.CommandText = "SELECT DISTINCT LastUpdatedLoanPaidDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')";
Assuming that there will be just 1 record fetched from the above query, The following code should add $500 to "loadPaid" column once every month
//Fetch "LastUpdatedLoanPaidDate" here
//This will be "LastUpdatedLoanPaidDate" coming from database i.e. dt[0][0].ToString(). Hard-coded here for simplicity
string strLastUpdatedLoanPaidDate = "07/29/2013";
DateTime lastUpdatedLoanPaidDate = Convert.ToDateTime(strLastUpdatedLoanPaidDate);
DateTime currDateTime = DateTime.Now;
//This will make sure that all the previous purchases are also handled and not just previous month's
//This is important when you are implementing new logic on existing data
int loanToBeAdded = (((currDateTime.Year - lastUpdatedLoanPaidDate.Year) * 12) + currDateTime.Month - lastUpdatedLoanPaidDate.Month) * 500;
//If loadToBeAdded is zero then need not update database
if (loanToBeAdded > 0)
{
String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", LastUpdatedLoanPaidDate = " + DateTime.Now.ToString();
sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')";
//Execute the above query here
}
There might be some things which I am missing depending upon your requirement. Also the update statement might need a tweak as I have not tested it but overall this should do the trick.
Hope this helped.
Regards,
Samar
You should also indicate in your table when you increased the loan for the last time and check this value, too. You could insert a new column lastLoanIncrease in the table LoanPortFolio as char(6) and save the month and year, when you increased it. Then before increasing again check for it.
You don't need a loop.
Your issue is in your conditional if
//DateTime loanDate = new DateTime(2000, 1, 18);
DateTime loanDueDate = Foo.GetLoanDueDate(loanId);
int loanDueMonth = loanDueDate.Month;
int currentMonth = DateTime.Now.Month;
if (currentMonth > loanDueMonth)
{
// update db
loanDate.AddMonths(1);
Foo.UpdateLoanDueDate(loanId, loanDate); // increase loan due date for next month so that the conditional is true next month.
}

Populating WPF datagrid from SQLCommand using stored procedure

I'm currently trying to populate a datagrid using a member of a class that uses SQLCommand to execute a stored procedure and return the results.
My class member (and where I believe the issues lies) is:
public DataView DisplayHealthIndicator(DateTime startDate, DateTime endDate)
{
string queryString =
"DECLARE #RC int"
+ "DECLARE #date_from datetime = dateadd(day, 0, datediff(day, 0, getdate()))"
+ "DECLARE #date_to datetime = dateadd(day, 0, datediff(day, 0, getdate()))"
+ "EXECUTE #RC = [Testing].[marlin].[support_retrieve_workflow_history] "
+ "#date_from "
+ ",#date_to"
+ "GO";
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (var cmd = new SqlCommand(queryString, connection))
{
connection.Open();
var reader = cmd.ExecuteReader();
var dt = new DataTable();
dt.Load(reader);
return dt.DefaultView;
}
}
}
and I'm calling this member using:
var db = new DatabaseHandle();
dataGridWorkflow.ItemsSource = db.DisplayHealthIndicator(DateTime.Now, DateTime.Now);
However! I'm currently receiving the error:
Incorrect syntax near #date_from
Must declare the scalar variable #RC
To a degree I understand the error - I believe that I can't declare variables in my sqlQuery string... but then, how do I do this?
I'm fairly sure that it doesn't have any bearing on this, but in case it does, this is the contents of the stored procedure:
create procedure marlin.support_retrieve_workflow_history
(
#date_from datetime,
#date_to datetime
)
as
select dateadd(day, 0, datediff(day, 0, e.event_date)) as 'Date',
c.setting_secondary 'Workflow Category' ,
d.setting_main as 'Error Type' ,
sum(e.event_count) as 'Total'
from marlin.support_events e
inner join marlin.support_config c
on e.event_category = c.setting_code
and c.config_code = 60
inner join marlin.support_config d
on e.event_type = d.setting_code
and d.config_code = 70
where e.event_date between #date_from and #date_to
group by
e.event_date,
c.setting_secondary ,
d.setting_main
cmd.Parameters["#ReturnValue"] contains the return value - you don't need to add a parameter in dynamic SQL
Add your parameters to the cmd
cmd.Parameters.AddWithValue("ParamName", Value);
Also change the cmd.CommandType (might not be called that, check members of cmd) to StoredProcedure
e.g.
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
using (var cmd = new SqlCommand(queryString, connection))
{
connection.Open();
cmd.CommandType = ??.StoredProcedure; // Can't remember what enum name is prob SqlCommandType or something
cmd.Parameters.AddWithValue("date_from", DateTime.blah.blah);
cmd.Parameters.AddWithValue("date_to", DateTime.blah.blah);
var reader = cmd.ExecuteReader();
var dt = new DataTable();
dt.Load(reader);
return dt.DefaultView;
}
}
Disclaimer: Some of these prop names, the name of the return value param might not be correct so check the docs :)
This post is a bit old...But, I wanted to share how I am dynamically populating the WPF DataGrid
private void Fill_DataGrid_ServiceName()
{
this.Cursor = Cursors.Wait;
// create an instance
DatabaseClass objDatabaseClass = new DatabaseClass(_connectionString);
// if we are able to open and close the SQL Connection then proceed
if (objDatabaseClass.CheckSQLConnection())
{
try
{
// create an instance. variable 'con' will hold the instance
SqlConnection con = new SqlConnection(_connectionString);
con.Open();
// Query to populate the Grid
string Query = #"SELECT
cm_mktdata_mdsservice_fits_to_finance_id_unique AS [Id Unique]
,cm_mktdata_mdsservice_fits_to_finance_MDSService_fits AS [FITS MDSService]
,cm_mktdata_mdsservice_fits_to_finance_MDSService_finance AS [Finance MDSService]
,'[ ' + CONVERT(varchar, user_detail_user_info_id_user) + ' ] ' + user_detail_user_info_nm_login AS [Last Modified By]
,cm_mktdata_mdsservice_fits_to_finance_record_version AS [Record Version]
,cm_mktdata_mdsservice_fits_to_finance_dt_modified AS [Dt Modified]
,cm_mktdata_mdsservice_fits_to_finance_ind_active AS [Ind Active]
FROM
dbo.v_mktdata_ui_mdsservice_fits_to_finance_detail
WHERE
cm_mktdata_mdsservice_fits_to_finance_ind_operational = 1
ORDER BY
cm_mktdata_mdsservice_fits_to_finance_MDSService_fits";
SqlCommand createCommand = new SqlCommand(Query, con);
createCommand.ExecuteNonQuery();
// transfer the results of createCommand to the dataGrid
SqlDataAdapter dataAdapter = new SqlDataAdapter(createCommand);
DataTable dt = new DataTable("vcm_mktdata_mdsservice_fits_to_finance");
dataAdapter.Fill(dt);
dataGrid_ServiceName.ItemsSource = dt.DefaultView;
dataAdapter.Update(dt);
con.Close();
// Enable the Refresh Grid Button
btn_RefreshGrid_ServiceName.IsEnabled = true;
// get DataGrid row count
lbl_dataGrid_RowCount_ServiceName.Content = dataGrid_ServiceName.Items.Count.ToString() + " rows";
//return true;
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
//return false;
}
}
else
{
MessageBox.Show("Connection not established to the SQL Server. " + Environment.NewLine + "The SQL Server may be offline or valid credentials are not yet granted.", "SQL Server Connection Error", MessageBoxButton.OK, MessageBoxImage.Error);
this.Close();
}
this.Cursor = Cursors.Arrow;
}
The DatabaseClass is as follows
class DatabaseClass
{
// Variables
private string _connectionString = "";
public DatabaseClass(string connectionString)
{
_connectionString = connectionString;
}
/// Check to see if Connection can be opened
///
/// Returns True if the connection can be open else it returns False
///
public bool CheckSQLConnection()
{
SqlConnection con = new SqlConnection(_connectionString);
try
{
con.Open();
con.Close();
return true;
}
catch (SqlException ex)
{
return false;
}
}
}
And for the connection string it will look as follows
public static string SQLDataSourceStr = "Data Source=MySQL-DB-DV;Initial Catalog=My_Data;Integrated Security=True";

Categories

Resources