Click here to Skip to main content
14,868,587 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Sir,

In my project I want to display data in wpf toolkit datagrid from database(SQL Server)


Code as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Windows.Controls ;
using System.Windows.Forms;
using System.ComponentModel;


private void Add_Click(object sender, RoutedEventArgs e)
{
try
{

SqlCommand cmd = new SqlCommand();
String str = "insert into State(Code,Name)values ('" + this.txtstatecode.Text + "','" + this.txtstatename.Text + "')";
cmd.CommandText = str;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
System.Windows.MessageBox.Show("Data Inserted Successfully");
DataTable dt = new DataTable();

String str1 = "select code,name from State";

cmd.Connection = conn;

cmd.CommandType = CommandType.Text;
cmd.CommandText = str1;
DataSet ds = new DataSet();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds,"State");
System.Windows.Forms.DataGrid statedg5 = this.FindName("statedg5") ;

statedg5.DataSource = ds;
statedg5.DataMember = "State";

}
catch (Exception e1)
{
System.Windows.MessageBox.Show(e1.Message);
}
finally
{
conn.Close();
}
}



But it shows error as follows

Error 1 Cannot implicitly convert type 'object' to 'System.Windows.Forms.DataGrid'. An explicit conversion exists (are you missing a cast?)


What can I do for this..

//statedg5 is my datagrid name


Pls say the correction

Advance thanks
Posted

1 solution

I assume you don't really want help. If you did, you'd tell us what line the error was on, what you did to try to fix it, etc.

wrote:
System.Windows.Forms.DataGrid statedg5 = this.FindName("statedg5") ;


This returns an object. You need to cast it. Use this.FindName("statedg5") as DataGrid and THEN you need to check if the object is null, to make sure it was found OK.

wrote:
String str = "insert into State(Code,Name)values ('" + this.txtstatecode.Text + "','" +


This is a nightmare. Apart from the obvious mess of writing SQL at random, if you give me access to this program in order to add a state, I can erase your database at will. You need to read up on parameterised queries and SQL injection.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900