Delo1987 Delo1987 - 6 months ago 19
SQL Question

SQL Help in .net WPF. retrieving multiple rows and getting the results into a data grid view

I'm making a program at work for people to retrieve gift card info.

I had a look around and there appears to be a few ways of doing this but I've not got one working yet. I'm trying to get some data for the history of a card (Multiple rows) out of a database and display it on a WPF form. I've changed the connection string and it used a variable

cardNumber
for the
where
clause. At the moment I've got the code posted below.

Edit: to clarify
ResultsGrid
is the Data Grid View on the UI

if (CardNumber.TextLength == 14)
{
SqlConnection sqlConnection1 = new SqlConnection("Data Source=XXX;Initial Catalog=USICOAL;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;

cmd.CommandText = "SELECT STORE_NO, WORKSTATION_NO, RTL_TRN_NO, AMOUNT, ACCT_TRN_TYPE_CODE, ACCT_TRN_DATETIME, OLD_BALANCE, NEW_BALANCE FROM ACCOUNT_TRANSACTION WHERE ACCOUNT_NO = " + cardNumber;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;


sqlConnection1.Open();

reader = cmd.ExecuteReader();
ResultsGrid.DataSource = reader;
ResultsGrid.Refresh();


sqlConnection1.Close();
}
//Else do nothing


private void CardNumber_TextChanged(object sender, EventArgs e)
{
// Try converting Value to int
try
{
cardNumber = long.Parse(CardNumber.Text);
} catch // Catch Exception thrown
{
Console.WriteLine("Unable To Convert to long");
CardNumber.Text = cardNumber.ToString();
}
}

Answer

Simply try as below, (between sqlConnection1.Open(); and close();)

SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt=new DataTable("ACCOUNT_TRANSACTION");
da.Fill(dt);
ResultsGrid.ItemsSource=dt.Defaultview;

I recommend to write codes manually with automatic intellisense support by visual studio meaning don't just copy above code because it is case sensitive.

and you don't need 3 lines,

reader = cmd.ExecuteReader();
ResultsGrid.DataSource = reader;
ResultsGrid.Refresh();
Comments