DataSet update in winform app - c#

I have some difficulty with the following: I have a dataset that I want to use to update the database when a change of value is made in the gridView. The dataset comes from the following method:
public static DataSet Display_all_members()
{
ds = new DataSet();
try
{
string query = "SELECT date_to, last_name ,first_name , member_pay FROM Member ";
conS.Open();
adapter = new SqlDataAdapter(query, conS);
adapter.Fill(ds, "To_display");
}
catch (Exception r)
{}
finally
{
conS.Close();
}
return ds;
}
In the form I do
ds2 = DAL.Display_all_members ();
dataGridView1.DataSource = ds2;
dataGridView1.DataMember = "To_display";
now I get to update and I do the following in the form
if (ds2.HasChanges() == true)
{
DAL.update(ds2);
}
In the method
public static void update(DataSet ki)
{
SqlCommandBuilder n = new SqlCommandBuilder(da);
da.Update(ds);
}
And it doesn’t work. What’s the problem?
This is the error: Update unable to find TableMapping['Table'] or DataTable 'Table'.

It might be just a typo, but your update method is using two different variables - DataSet ki, and da in the DataAdapter.Update() call.
Try this:
protected void update(DataSet ds)
{
da.Update(ds, 'To_display")
}
From DataAdapter DataTable and DataColumn Mappings (ADO.NET):
"If you do not specify a TableName or a DataTableMapping name when calling the Fill or Update method of the DataAdapter, the DataAdapter looks for a DataTableMapping named "Table". If that DataTableMapping does not exist, the TableName of the DataTable is "Table"."
If you're using the same DataSet that you originally filled, you'll probably want to keep specifying the table name where required to avoid this error.

Related

protected DataSet against SQL Inejection

I want to create a class that I can get datatable of specific table given in the parameter of the constructor.
But how I can do it without it being vulnerable to SQL Injections?
I would've done something like this: (But you can't use those statements like that)
public class SqlClass
{
DataTable dt;
string table;
public SqlClass(String table)
{
this.table = table;
SqlConnection c = new SqlConnection();
c.conOpen();
MySqlCommand msc = new MySqlCommand("SELECT * FROM #tableName", c.Con); //Cant do that
msc.Parameters.AddWithValue("#tableName", table);
DataSet ds = c.getDataSet(msc, table);
this.dt = ds.Tables[table];
c.conClose();
}
public DataTable Dt { get => dt; set { dt = value; } }
}
Any other working alternative that won't harm me? Thanks.

Pass dropdown list into a method

I have the following code LoadRegistrations(); to populate a DropDownList with values from a SQL database.
I will be likely to use this several times in different places so wanted to write a method to take care of it, instead of copying this method and changing minor details.
I've got as far as populating the DataTable but I'm not sure how to go about passing a DropDownList & the DataTextField + DataValueField into it and binding the data. Please explain what I have to do
Original Method
private void LoadRegistrations()
{
DataTable reg = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString1"].ToString()))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("select vehicleID, regNo from dbo.Vehicles order by regNo Asc", con);
adapter.Fill(reg);
ddreg.DataSource = reg;
ddreg.DataTextField = "regNo";
ddreg.DataValueField = "vehicleID";
ddreg.DataBind();
}
catch (Exception ex)
{
// Error handling to be done
}
}
}
New Method
private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
adapter.Fill(dt);
//What do I do here? I want to bind to a dropdown list passed into this method
}
catch (Exception ex) { }
}
return dt;
}
ASP to generate dropdown
<asp:DropDownList ID="ddreg" CssClass="form-control" runat="server" AppendDataBoundItems="true">
<asp:ListItem Text="<Select Registration Number>" Value="0" />
</asp:DropDownList>
You've created a method with parameters:
private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query)
If you want to pass a DropDownList to that method, do exactly what you already do and add a parameter:
private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query, DropDownList myDropDownList)
Then in the method you can refer to myDropDownList:
myDropDownList.DataSource = dt;
myDropDownList.DataBind();
When calling the method, you'd pass it the DropDownList you want to modify:
PopulateDropDown(someConnectionString, someDataTableYouDoNotUse, someQuery, ddreg);
private DataTable PopulateDropdown(string connectionString, DataTable datatable, string query, System.Web.UI.WebControls.DropDownList yourDropdownList)
{ 
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
adapter.Fill(dt);
yourDropdownList.DataSource = dt;
yourDropdownList.DataBind();
return dt;
}

GridView doesn't show data

private void fill()
{
adptr = new OleDbDataAdapter(#"SELECT * FROM LibraryInfo WHERE First_Name='"+LoginName+"'", cn);
//LoginName is a string variable for displaying users info after the login
ds.Clear();
adptr.Fill(ds);
dataGridView1.DataSource = "";
dataGridView1.DataSource = ds.Tables[0];
}
After the database updated, GridView didn't show data.
Taken from this msdn article on the DataBind Property.
ASP EXAMPLE
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
AuthorsGridView.DataSource = ds;
AuthorsGridView.DataBind();
}
else
{
Message.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Message.Text = "Unable to connect to the database.";
}
return ds;
}
This snippet shows you how to (a) bind your dataset to a gridview, by assigning it using the Databind method.
The site also says:
Use the DataBind() method to bind data from a data source to the GridView control. This method resolves all data-binding expressions in the active template of the control.
SOLUTION
I would like to reference the line saying:
AuthorsGridView.DataBind();
which actually binds the data to the control.
SIDE NOTE
To protect yourself from SQLi, you should read up on SQL Parameters, and not direct concatenation.
WINFORM EXAMPLE
Tutorial was found: here
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
//create the database query
string query = "SELECT * FROM MyTable";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
Also:
//the DataGridView
DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dgView.DataSource = bSource;
Use are missing to call databind method here.Use following code :
DataAdapter adapter=new DataAdapter(SqlCommand,SqlConn);
DataTable tbl=new Datatable();
adapter.Fill(tbl);
GridView1.DataSource=tbl;
GridView1.DataBind();//This line is missing in your code
try with this format?

cant fetch table from database in datagridview

Here's a code for fetching only one column from database table to dategridview. I am getting following error at line no 6 of the following code.
"No value given for one or more required parameters."
My code:
private void marks_entry_Load(object sender, EventArgs e)
{
global.connect();
OleDbDataAdapter da = new OleDbDataAdapter("select Name from 5CSEA", global.con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
global.con.Close();
}
#sangram, you can create table like 5CSEA. check your global.con connection status, and use try catch

DataAdapter Fill without command

I'm trying to fill my dataadapter without using a command. I have a dataset which I manually populated but when I try to attach this dataset with my dataAdapter I'm gettin "The Select command property has not been initialized before calling 'Fill'". This is my code does anyone has an idea for this ?
Thanks
OleDbDataAdapter ad1=new OleDbDataAdapter(cmd);
OleDbDataAdapter ad2=new OleDbDataAdapter(cmd2);
OleDbDataAdapter ad3 = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable db1=new DataTable();
DataTable db2=new DataTable();
DataTable db3 = new DataTable();
ds.Tables.Add();
ad1.Fill(db1);
ad2.Fill(db2);
int i;
foreach (DataRow r in db2.Rows)
{
i = 0;
foreach (DataRow rc in db1.Rows)
{
if (r[0].ToString() == rc[0].ToString())
{
i = 1;
}
}
if (i == 0) { ds.Tables[0].ImportRow(r); }
}
ad3.Fill(ds);
I'm not entirely sure what you are trying to accomplish here, it is unclear from your description. You already have placed data in the DataSet with:
ds.Tables[0].ImportRow(r);
Also, a Data Adapter of any type has to have at the very least a SELECT command associated in order for it to fill a Data Table or Data Set.
Could you describe your objective a bit more clearly? Are you trying to add a table to the dataset? Fill it from some external source? View the rows you imported?

Categories

Resources