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?
Related
So, I am trying to change the column type of table to bool but I don't know if this is possible because I used data adapter to fill the table as in the following code
private void GetData(string selectCommand)
{
try
{
// Create a new data adapter based on the specified query.
dataAdapter = new OleDbDataAdapter(selectCommand, conn);
OleDbCommandBuilder commandBuilder = new OleDbCommandBuilder(dataAdapter);
// Populate a new data table and bind it to the BindingSource.
System.Data.DataTable table = new System.Data.DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
//table.Columns["Status"].DataType = typeof(bool);
if (table.Rows.Count > 0)
bindingSource1.DataSource = table;
else
{
MessageBox.Show("There is no such Data.", "No Result");
showAll();
}
}
as you can see the commented line was a wrong way. Can someone help?
Sharing MSDN Link for your reference. Try changing the data type of the DataColumn using the GetType() method.
DataColumn statusColumn = table.Columns["Status"];
statusColumn.DataType = System.Type.GetType("System.Boolean");
I'm trying to insert new records into the source table from the C# interface grid view....
But when I retrieve the records with the buttonclick code shown below... Im getting records in the gridview but no option for inserting new records(screen shot attached).. where as i can update the reocrds from the grid view.
Is there any option or property for enabling the insertion option in the gridview ?
Buttonclickcode :
private void RetrieveRules_button_Click(object sender, EventArgs e)
{
this.dataGridView.DataSource = null;
this.dataGridView.Rows.Clear();
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = #" Select TOP 1 * FROM " + schemaName + "[ERSBusinessLogic] ORDER BY ERSBusinessLogic_ID DESC";
con.Open();
cmd1.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(cmd1);
DA.Fill(dt);
dataGridView.DataSource = dt;
con.Close();
}
Thanks
CRUD Operations using DataGridView, DataTable and DataAdapter
To let the user add, delete or edit rows with DataGridView:
Set AllowUserToAddRows property to true or in DataGridView Tasks, check Enable Adding
Set AllowUserToDeleteRows property to true or in DataGridView Tasks, check Enable Deleting
Set ReadOnly property to false or in DataGridView Tasks, check Enable Editing
To let the user save changes using a SqlDataAdapter:
Create a SqlDataAdapter using a select statement and a connection string.
You should have valid InsertCommand, DeleteCommand and UpdateCommand for your data adapter. Create valid commands using a SqlCommandBuilder.
Load data to a DataTable using data adapter.
Set data table as DataSource of DataGridView
Save changes when you need using SqlDataAdapter.Update by passing data table to the method.
Code
DataTable table;
SqlDataAdapter adapter;
private void Form1_Load(object sender, EventArgs e)
{
//Create adapter
var connection = #"your connection string";
var command = "SELECT * FROM Table1";
adapter = new SqlDataAdapter(command, connection);
//Create Insert, Update and Delete commands
var builder = new SqlCommandBuilder(adapter);
//Load data
table = new DataTable();
adapter.Fill(table);
//Bind the grid to data
this.dataGridView1.DataSource = table;
//Enable add, delete and edit
this.dataGridView1.AllowUserToAddRows = true;
this.dataGridView1.AllowUserToDeleteRows = true;
this.dataGridView1.ReadOnly = false;
}
private void saveButton_Click(object sender, EventArgs e)
{
//Save Data
adapter.Update(table);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
adapter.Dispose();
}
Note
You don't need that ExecuteNonQuery. You only need a connection string and a command text. Then you can create a data adapter. Then you even don't need to manage opening and closing the connection, data adapter manages it.
When you load data using SELECT TOP 1 *, if you add data and save, you can't see updates next time you load the data because you load only a single record.
Code is using ExecuteNonQuery, it returns no of rows affected not the results your query returns.
Use ExecuteReader instead.
var reader = cmd1.ExecuteReader();
DataTable dt = new DataTable();
dtLoad(reader);
Is there any option or property for enabling the insertion option in
the gridview
dataGridView1.ReadOnly = false;
dataGridView1.EditMode = DataGridViewEditMode.EditOnF2; //if you want to edit on F2.
I am a newbie in C# so I don't know if I will address my problem correctly so please bear with me. I have 3 DataGridViews (datagridview1, datagridview2, datagridview3). All are located in the same window but they are in a different tab (I have a tab control).
The purpose of each DataGridView is to display data for three tables from database. So every time I click a button, it retrieves data. But here is my problem, when datagridview1 displays the data after clicking the button, then I go to the next tab and click again the retrieve button, the datagridview2 shows the data that was displayed to datagridview1. Same thing to datagridview3.
I'm using DataTable as the data source for those DataGridViews. And somewhere in my script the query will change so I think there's no problem with the query. What I found is that the DataTable does not clear it's data even when the query already changed.
I'm using WinForms, please help me. Thanks.
Here is the code I used in binding the datagridview to a datasource:
currentdatagrid.DataSource = execute.InitConn2(query, CompleteTablename);
Note: "execute.InitConn2(query, CompleteTablename)" will return a datatable.
Try doing something like the following example and see if it works for you. The static method GetData returns a new data table each time. You need to update the SqlConnection with your own connection string.
public static void Main(string[] args)
{
DataGrid dg1 = new DataGrid();
DataGrid dg2 = new DataGrid();
DataGrid dg3 = new DataGrid();
dg1.DataSource = GetData("select * from table1");
dg1.DataBind();
dg2.DataSource = GetData("select * from table2");
dg2.DataBind();
dg3.DataSource = GetData("select * from table3");
dg3.DataBind();
}
public static DataTable GetData(string sqlQuery) {
try
{
DataTable dt = new DataTable();
// set your connection here
SqlConnection conn = new SqlConnection("");
// execute query with your connection
SqlDataAdapter adapt = new SqlDataAdapter(sqlQuery, conn);
// open connection, fill data and close
conn.Open();
adapt.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex) {
throw ex;
}
}
To use a dataset use the following:
public static void Main(string[] args)
{
DataGrid dg1 = new DataGrid();
DataGrid dg2 = new DataGrid();
DataGrid dg3 = new DataGrid();
DataSet ds = GetData(#"select * from table1;
select * from table2;
select * from table3");
dg1.DataSource = ds.Tables[0];
dg1.DataBind();
dg2.DataSource = ds.Tables[1];
dg2.DataBind();
dg3.DataSource = ds.Tables[2];
dg3.DataBind();
}
public static DataSet GetData(string sqlQuery) {
try
{
DataSet ds = new DataSet();
// set your connection here
SqlConnection conn = new SqlConnection("");
// execute query with your connection
SqlDataAdapter adapt = new SqlDataAdapter(sqlQuery, conn);
// open connection, fill data and close
conn.Open();
adapt.Fill(ds);
conn.Close();
return ds;
}
catch (Exception ex) {
throw ex;
}
}
I have a gridview which populates its data from a MS Access Database. I have enabled the "Selecting" on the gridview, and have created a delete button. I would like to select a row on the gridview and delete the data from the gridview as well as the database when the delete button is pressed. Below is my attempted code, but its not working.
Error that I am getting is "Object reference not set to an instance of an object" on the line of code where it says, "myDataSet.Tables["Users"].Rows[i].Delete();"
Webservice method:
//Modifies the datbase
[WebMethod]
public string DatabaseUserModify(DataSet myDataset)
{
string database = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|/studentdb.accdb;Persist Security Info=True";
OleDbConnection myConn = new OleDbConnection(database);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from Users",
myConn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(myDataAdapter);
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
myConn.Open();
myDataAdapter.Update(myDataset, "Forum");
myConn.Close();
return "done";
}
Website:
protected void DeleteButton(object sender, EventArgs e)
{
Service myService = new Service();
myDataSet = myService.AdminGetUserTable();
int i = GridView1.SelectedIndex;
myDataSet.Tables["Users"].Rows[i].Delete();//This is where I am getting error
GridView1.DataSource = myDataSet;
GridView1.DataBind();
myService.DatabaseUserModify(myDataSet);
}
Your myDataSet is probably being lost after the postback. You must have to save the myDataSet in page's ViewState in order to retain it's value across postbacks. Like this:
public DataSet myDataSet
{
get
{
return ViewState["myDataSet"] != null ? (DataSet)ViewState["myDataSet"] : null;
}
set
{
ViewState["myDataSet"] = value;
}
}
But, it is a worst idea to save large data/objects in a ViewState.
I have a WPF Browserapplication which gets data stored on a SQL Server, stores it in a DataTable and displays it in a DataGrid. Now I want to have a TextBox where you can search entries in the DataTable but when I load the Application I'm getting an error telling me, that the row [Company] cannot be found.
I think the problem is, that the DataTable isn't yet filled when the filter is being applied to the DataTable. Can someone please give me a hint how to make this working?
DataTable dt = new DataTable();
public Page1()
{
InitializeComponent();
showSQLData();
}
private void showSQLData()
{
string sqlConnectionString = #"blabla";
string sqlCommandString = "SELECT * FROM Excel_import";
using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
{
SqlCommand cmd = new SqlCommand(sqlCommandString, sqlConnection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
dataGridSQLData.ItemsSource = dt.DefaultView;
}
}
private void textBoxSearch_TextChanged(object sender, TextChangedEventArgs e)
{
dt.DefaultView.RowFilter = string.Format("Company LIKE '%{0}%'", textBoxSearch.Text);
}
Based on you latest comment I would guess that textBoxSearch_TextChanged is being fired from within the InitializeComponent() call. You could check that dt.Rows.Count > 0 in textBoxSearch_TextChanged and return if that condition is not met.