Selecting a row in Gridview and deleting it - Asp.net - c#

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.

Related

How to print selected row from DataGridView in C# with SQL

Using the following code the first row in SQL is printed only, How can I print selected row from DataGridView in C# with SQL:
public partial class PrintScreen : Form
{
SqlConnection con = new SqlConnection(#"Server = TEST;DataBase=Registration;Integrated Security=true;");
SqlDataAdapter da;
DataTable dt = new DataTable();
public PrintScreen()
{
InitializeComponent();
da = new SqlDataAdapter("select * from data_graduation", con);
da.Fill(dt);
this.dataGridView1.DataSource = dt;
}
private void Print_ys_ar_cert_Click(object sender, EventArgs e)
{
Print_ys_ar_cert frm = new Print_ys_ar_cert();
da = new SqlDataAdapter("select * from data_graduation where ID_gra = '" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'", con);
da.Fill(frm.RegistrationDataSet1.data_graduation);
frm.reportViewer2.RefreshReport();
frm.Show();
}
}
Currently you are passing value of Cells[0] of first row of the grid, you need to pass value of selected row:
if(dataGridView1.SelectedRows.Count>0)
{
var selectedValue = dataGridView1.SelectedRows[0].Cells[0].ToString();
//rest of code
}
Since you have loaded the row from database once, you don't need to load it again from database, you can simply add it to the data table which is data source of the report this way:
var row = ((DataRowView)(dataGridView1.SelectedRows[0].DataBoundItem)).Row;
frm.RegistrationDataSet1.data_graduation.Rows.Add(row.ItemArray);
//rest of code

The data source does not support server-side data paging. .toList() is not working

I'm trying to load some data from a database, and to filter them using this method.
Now, i want also to show them by pages, especially at the non-filtered part.
I used a DataAdaptor to fill up a dataset table, on which I'm making my filtering.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
OracleConnection con = new OracleConnection(CS);
string query = "select * from table1";
OracleDataAdapter dataAdapter = new OracleDataAdapter(query, con);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "mytbl");
Session["DATASET"] = dataSet;
GridView1.DataSource = from dataRow in dataSet.Tables["mytbl"].AsEnumerable()
orderby dataRow["ID"]
select new guards
{
ID = Convert.ToInt32(dataRow["ID"]),
Nume = dataRow["NUME"].ToString()
};
GridView1.AllowPaging = true;
GridView1.DataBind();
}
You will have to tell ASP.NET how to page. in this case it is .Skip().Take()

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?

C# WPF - Live search in a DataTable

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.

Inserting a row into a database

I'm having some difficulties understanding how databases and SQL works. I'm trying to update a certain row in my database. I can remove a row, but when i use the InsertAt function, it is always appended to the end of my database. Also, it's assigned a new identifier key.
I would like to just edit what is already in there. No need for a new key, and I would like the edited row to stay where it was.
I've tried to strip down the code to show the the problem.
public partial class MainWindow : Window
{
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter da;
DataSet sessions;
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
con = new System.Data.SqlClient.SqlConnection();
sessions = new DataSet();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\md\\PokerDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
string sql = "SELECT * From Sessions";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
da.Fill(sessions, "Sessions");
con.Close();
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataTable dt = sessions.Tables["Sessions"];
DataRow table = sessions.Tables["Sessions"].NewRow();
table[0] = "Some Data";
table[1] = "Some Data";
table[2] = "Some Data";
table[3] = 2;
table[4] = 3;
sessions.Tables["Sessions"].Rows[2].Delete();
sessions.Tables["Sessions"].Rows.InsertAt(table, 2);
da.Update(sessions, "Sessions");
}
}
Could anyone help me figure out what I'm doing wrong?
Error
You are creating a new row using
DataRow table = sessions.Tables["Sessions"].NewRow();
This will add new row to you database, it's not going to update a row.
Solution
To update a row you need to select that specific row, something like:
DataRow table = sessions.Tables["Sessions"].Rows[0];
then modify the row data and then update da.
This will the update existing row in your database.

Categories

Resources