I am new to coding and trying to learn but have come across an error which is very annoying, I am trying to populate a data grid with the value selected from a dropdownlist and I am not sure why it is throwing up this error.
The program takes and enters into the Database the information fine, but when I expanded on the program to add a Datagridview so the user could see the entered information for a specific driver selected from the combobox
using (SqlConnection sqlcon = new SqlConnection(connstring))
{
DataTable dt = new DataTable();
sqlcon.Open();
using (SqlCommand cmd = new SqlCommand("display", sqlcon))
{
cmd.Parameters.AddWithValue("#driver", driverSelect.SelectedValue);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
sqlcon.Close();
}
dataGridView1.DataSource = dt;
}
this is the error I get
"System.ArgumentException: 'No mapping exists from object type System.Data.DataRowView to a known managed provider native type.'" from this line. SqlDataReader reader = cmd.ExecuteReader();
Related
I am trying to edit a cell in a RadGridView which has a datasource set from data from an SQL view.
What I was hoping to do was to populate the grid from the view, allow edits then manually update the associated tables when a user click an "Update" button.
As soon as the user enters data into a cell and leaves the cell is presents with an error "Specified method is not supported".
I assume it's trying to update the datasource with the new value so I am trying to work out how to tell it not to.
I am populating the table with:
using (SqlConnection con = new SqlConnection(mydatasource))
{
con.Open();
SqlCommand cmd = new SqlCommand("select SRID, Name, Result from EditBatchResultsView where SRID = " + drpSRID.Text, con);
SqlDataReader reader = cmd.ExecuteReader();
radGridView1.DataSource = reader;
}
According to RadGrid data binding documentation, the DataSource property accepts instances of the following types:
DataSet
DataTable
DataView
Array of DataRow
Any object collection that implements these interfaces:
IListSource
IList
IEnumerable
ICustomTypeDescriptor
Based from reference inspection, SqlDataReader doesn't supported because it doesn't implement those interfaces mentioned above, hence NotSupportedException has thrown when binding SqlDataReader contents into DataSource property directly.
As a workaround, you may create new DataTable instance and fill its contents from SqlDataReader like this:
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(mydatasource))
{
con.Open();
SqlCommand cmd = new SqlCommand("select SRID, Name, Result from EditBatchResultsView where SRID = " + drpSRID.Text, con);
SqlDataReader reader = cmd.ExecuteReader();
// fill DataTable contents
dt.Load(reader);
// assign DataTable as data source instead
radGridView1.DataSource = dt;
}
// DataBind goes here
Note:
The string concatenation to build SQL query may prone to SQL injection. Using parameters when passing server control value to SQL query is more recommended way:
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(mydatasource))
{
con.Open();
SqlCommand cmd = new SqlCommand("select SRID, Name, Result from EditBatchResultsView where SRID = #SRID", con);
cmd.Parameters.Add("#SRID", SqlDbType.VarChar).Value = drpSRID.Text;
SqlDataReader reader = cmd.ExecuteReader();
// fill DataTable contents
dt.Load(reader);
// assign DataTable as data source instead
radGridView1.DataSource = dt;
}
Related issue:
Populate data table from data reader
I'm working on a school development project and I'm quite new to development. I have been reading online but can't find the answer I'm looking for.
So far I have created a listbox in my Windows Forms application which I want to select all the values from one of my columns, and these should work as a inparameter to display data in my dataGridView based on the parameter.
I have created 70% of my project and this functionality is what is left. My database is in Azure and I can write to it and add new rows, but I can't read anything to my application when I run it.
code for listview, at first I just want to be able to select. Later on somehow write the choosen parameter to a variable that I can use as a condition in my dataGridView.
This is the code for my gridview so far I just want to display all data in it, but it's not showing anything.
namespace MyNamespace
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString;
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand
(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue
(
"#companyName",
textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
MessageBox.Show("GJ");
}
}
// The code that is not filling my datagrid
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
}
}
My connection string is working it's already being able to insert data to the tables that I have.
The problem why you Grid isn't shown any data is that you try to bind a SqlDataReader to it. This isn't working, because the Grid doesn't support this as DataSource.
What you need as DataSource is DataTable, IList<T>, IBindingList<T>. In your case the DataTable would be the easiest solution. Try this out:
protected void DataEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select firstname,lastname FROM employees",con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
Notice that Methods are written Uppercase in C#. Further notice that you don't need to close the connection manually if you use a using-block. On the end of the using-block it's automatically closed/disposed.
public DataTable DisplayHolidays(int empid)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("ComputeHoliday", myCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = empid;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
temp2 = rd[0].ToString();
}
return dt;
}
This is my code I had a problem/error with this part. This code is in the class not in the form load. It cannot display the data in the textbox. I'm using temp2 to store the data in the selected row but it's not yet working.
I assume that you're getting an exception at cmd.ExecuteReader().
Note that you must open the connection before you can use the command in cmd.ExecuteReader(). DataAdapter.Fill does not need an open connection, the dataadapter will open/close it implicitly.
MSDN:
The connection object associated with the SELECT statement must be
valid, but it does not need to be open. If the connection is closed
before Fill is called, it is opened to retrieve data, then closed. If
the connection is open before Fill is called, it remains open.
Why do you use DataAdapter.Fill(DataTable) and also Command.ExecuteReader? You need just one way to get the data. If you already have filled a table:
If(dt.Rows.Count > 0)
{
temp2 = dt.Rows[0].Field<string>(0);
}
If you don't use the DataAdapter and the DataTable but only the reader:
using(SqlDataReader rd = cmd.ExecuteReader())
{
if(rd.HasRows)
{
rd.Read();
temp2 = rd.GetString(0);
}
}
I am using c# and i don't know how to write the data from c# in the HTML (to be available on the browser)
Here is my code :
public void searchbutton_Click(object sender , EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAX-PC\\SQLEXPRESS;Initial Catalog=newSchool;Integrated Security=True");
SqlCommand cmd = new SqlCommand("search_name", conn);
cmd.CommandText = "exec search_name #name";
cmd.Parameters.AddWithValue("#name", search.Text);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
conn.Close();
}
I want to know what to write in the HTML file to take the data from the reader
Thanks
You probably want to use a GridView control to display the data. http://msdn.microsoft.com/en-us/library/aa479342.aspx
Hope this helps
After the execute reader command do the following lines code for binding the data to the grid.
Also add a gridcontrol to the HTML to which the data has to be rendered.
DataSet ds = new DataSet();
DataTable dt = new DataTable("Table1");
ds.Tables.Add(dt);
ds.Load(read, LoadOption.PreserveChanges, ds.Tables[0]);
gridControl1.DataSource = ds.Tables[0];
I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.
SqlConnection DBConnection = new SqlConnection(ConnectionString);
//Opens the connection
DBConnection.Open();
//Creates a string to hold the query
string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";
//Creates an SQLCommand object to hold the data returned by the query
SqlCommand queryCommand = new SqlCommand(query, DBConnection);
//Uses the aforementioned SQLCommand to create an SQLDataReader object
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Creates a DataTable to hold the data
DataTable dataTable = new DataTable();
//This part actually loads the data from the query into the table
dataTable.Load(queryCommandReader);
dgvOutput.DataSource = dataTable;
The other example:
using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
{
DataTable Table = new DataTable();
newDA.Fill(Table);
dgvOutput.DataSource = Table;
}
You might try this or something similar:
SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text;
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;