Change DataBase using DataGrid - wpf

I want to output data from DataBase to DataGrid, using ADO.NET.
Can you tell me how to do that?
When I'm writing something in dataGrid it's changing in database. I use WPF, .NET 4.0.
Code:
class ThemeEditor
{
private SqlDataAdapter da;
private DataSet ds;
private SqlConnection cn;
public ThemeEditor(DataGrid dg)
{
SqlCommand cmd;
string source = "server=(local); integrated security=SSPI; database=tests";
string reqest = "SELECT Theme,Stuff FROM Themes";
cn = new SqlConnection(source);
da = new SqlDataAdapter();
ds = new DataSet();
cmd = new SqlCommand(reqest, cn);
da.SelectCommand = cmd;
da.Fill(ds, "Theme");
dg.ItemsSource = ds.Tables["Theme"].DefaultView;
}
}

maybe it'll be helpfull!
http://support.microsoft.com/kb/307587
or this... http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3adacd01-f08f-4059-bbce-bff736a5188e

Related

How do I check for duplicates and remove them on each data entry in SQL Server, WPF, C#?

I'm practicing SQL integration in C# by creating a Zoo Management app. Users can input a new name of Zoo to be listed on a ListBox. I want the app to check whether the new zoo is already listed or not (checking for duplicates), and if there is a duplicate, it will remove the newly added zoo.
I can't figure out the SQL query to do that.
Here I create a tiny simulation app to ask about the duplicates removing method.
Table name is TEST with just 2 columns Id and Name.
In the WPF there is a ListBox which lists all names, 2 buttons (Add and Remove names), and one TextBox to type in the want-to-be added name.
I've tried various methods and I just can't seem to get it to work.
public partial class MainWindow : Window
{
SqlConnection sqlConnection;
public MainWindow()
{
string connectionString = ConfigurationManager.ConnectionStrings["DeleteDuplicateTest.Properties.Settings.DB1ConnectionString"].ConnectionString;
sqlConnection = new SqlConnection(connectionString);
InitializeComponent();
ShowNames();
}
// This is where I got lost
public void CheckForDuplicates()
{
}
public void ShowNames()
{
string query ="select * from TEST";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
using (sqlDataAdapter)
{
DataTable names = new DataTable();
sqlDataAdapter.Fill(names);
listNames.DisplayMemberPath = "Name";
listNames.SelectedValuePath = "Id";
listNames.ItemsSource = names.DefaultView;
}
}
private void Add_Click(object sender, RoutedEventArgs e)
{
if (myTextBox.Text != "")
{
string query = "Insert into TEST values (#Name)";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Name", myTextBox.Text);
sqlCommand.ExecuteScalar();
sqlConnection.Close();
ShowNames();
CheckForDuplicates();
}
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
if (listNames.SelectedValue != null)
{
string query = "Delete from TEST where Id=#Name";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
sqlConnection.Open();
sqlCommand.Parameters.AddWithValue("#Name", listNames.SelectedValue);
sqlCommand.ExecuteScalar();
sqlConnection.Close();
ShowNames();
CheckForDuplicates();
}
}
}

How to save XML data in SQL Server?

In my table there is one XML column. I want to fetch the XML data in one textbox and make some corrections and update it:
private void button2_Click(object sender, EventArgs e)
{
con.Open();
string str = "select C1 from TableName where C2='" + txt1.Text+ "'";
SqlCommand cmd1 = new SqlCommand(str, con);
XmlReader xml = cmd1.ExecuteXmlReader();
xml.Read();
txt2.Text = xml.ReadOuterXml();
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(txt2.Text);
}
Now I want to make some changes and update it in my database. When I try to change in textbox it does not work. How can I make changes and update in database? Please help
Update Like this
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "Update TableName set C1 = #C1 where C2 = #C2 ";
command.Parameters.AddWithValue("#C1", Textbox2.Text);
command.Parameters.AddWithValue("#C2", Textbox1.text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}

Populating ListBox using parameterized query on VB.Net

I have the following code that involves populating a ListBox. How can I parameterize the query to prevent SQL injection?
sqlCon = New SqlConnection(strConn)
sqlCon.Open()
Dim sql As String = "SELECT * FROM employees where id = & textbox1.text &"
Dim adapter As New SqlDataAdapter(sql, sqlCon)
Dim da As New DataTable
adapter.Fill(da)
ListBox1.DisplayMember = "employees"
ListBox1.DataSource = da
ListBox1.ValueMember = "employees"
sqlCon.Close()
Maybe this will help:
Using sqlCon As SqlConnection = New SqlConnection(strConn)
sqlCon.Open()
Dim sql As String = "SELECT * FROM employees WHERE id = #id"
Dim adapter As SqlDataAdapter = New SqlDataAdapter(sql, sqlCon)
adapter.SelectCommand.Parameters.Add(New SqlParameter("#id", textbox1.Text))
Dim da As New DataTable
adapter.Fill(da)
ListBox1.DisplayMember = "employees"
ListBox1.DataSource = da
ListBox1.ValueMember = "employees"
End Using
It's better to enclose the code inside the Using so that the SqlConnection will be disposed even an exception is thrown. Also instead of using SELECT *, you may want to specify the column names.

how to bind datagridview in ado.net

i want to bind datagridview on form load using ado.net "Child list for field Physio_cureTable cannot be created". error iam paste here my code please give me suggestions or help
con = new SqlConnection("Data Source=ADMIN\SQLEXPRESS;Initial Catalog=PhysioCure; Integrated Security=true");
sda = new SqlDataAdapter("select RegisterNo,RegistrationDate,Stimulation,PationName,DateOfBirth,ContactNo,Occupation,Age,Sex,Weight,Chief_Complain,Investigation_Result,PastHistoryAny,Physical_Examination,Ref_By_Doctor,Medications,Prognosis,Electro_Therapy,Neuro_Rehabilitation,Ortho_Rehabilitation,Cardio_Pulmonery_Rehabilitation,Sports_Rehabilitation from Physio_cureTable where Syncoperation <>'D'",con);
ds = new DataSet();
sda.Fill(ds);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Physio_cureTable".ToString();// error coming this line
dataGridView1.DataMember = "Physio_cureTable".ToString();
Physio_cureTable has to be a column name you have binded with the DataGridView
dataGridView1.DataMember = "RegisterNO".ToString();

Fill observableCollection directly from sql server

I would like to know if there is any way to fill ObservableCollection directly from SQL server.
Currently I am loading my data into DataTable (using sqlDataAdapter) and do a conversion to ObservableCollection manually and it very inefficient.
How it can be done?
OK, I have found a way to do this:
It can be done using SqlDataReader.
public ObservableCollection<DataItem> LoadCategoriesData()
{
Command = new SqlCommand(StoredProcedure, Connection);
Command.CommandType = CommandType.StoredProcedure;
ObservableCollection<DataItem> myColl = new ObservableCollection<DataItem>();
Connection.Open();
SqlDataReader reader = Command.ExecuteReader();
while (reader.Read())
{
int mainCatID = reader.GetInt32(0);
string categoryName = reader.GetString(1);
//adding row data to observable
myColl.Add(new DataItem(mainCatID, categoryName));
}
Connection.Close();
return myColl;
}

Resources