I have populated the value for a datatable by using the value in a database. The data willl get populated into database on a button click. Can anybody tell how to check the value in the datatable which is populated.
I am using visual studio and coding in c#
The code for populating the datatable is as shown below :
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
var sql = #"select scriptname,accnum,Quantity,price from transac where transactio = 'Sell'";
var dataAdapter = new System.Data.SqlClient.SqlDataAdapter(sql, conn);
var dataTablesell = new DataTable();
dataAdapter.Fill(dataTablesell);
}
catch (System.Data.SqlClient.SqlException sqlEx)
{
Response.Write("error" + sqlEx.ToString());
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
DataTable has a very nice DebuggerVisualizer. Set a breakpoint after dataAdapter.Fill(dataTablesell); line; when the breakpoint is hit, hover cursor over dataTablesell to open a debug view and click magnifier button (O-) to open visualizer
You can iterate through rows of DataTable to get the value in each row for given columns.
foreach(DataRow row in dataTablesell.Rows)
{
Debug.WriteLine(row["scriptname"].ToString()); //use cell value where you want
Debug.WriteLine(row["accnum"].ToString()); //use cell value where you want
}
You can also bind the DataTable to DataGridView to see the rows in the DataTable. This MSDN article How to: Bind Data to the Windows Forms DataGridView Control explains how you would do that.
got the answer...
Instead of using Console.WriteLine as Adil has said, I used Response.Write, The code is
foreach (DataRow row in dataTablesell.Rows)
{
Response.Write(row["scriptname"].ToString());
Response.Write(row["accnum"].ToString());
}
Related
Edit 2: Turns out it only gives a NullReferenceException the first time. After that, it says that I am not allowed to change the ConnectionString property, even though I think I have closed it in the right places.
Thanks for taking the time to read this.
I am working on a WinForms application that uses an MS Access database, and I am currently having problems with an entry deletion feature I made.
So, I have a DataGridView that switches between 3 tables on a button click, and I have a function that deletes a row on a table that is currently open by clicking a button that is at the end of the row.
When I open my first table, and try to delete a row, it works just fine. However, if I open a different table afterwards and try to delete an entry, or even go back to the first table I opened, I get a NullReferenceException in the deletion function.
Here is the code to display one of the tables in DataGridView.
public DataTable Read()
{
connection.ConnectionString = connectionString;
OpenConnection(); //connection.Open() inside an if statement
dataTable.Clear();
OleDbCommand readStudentCommand = new OleDbCommand("select * from Students", connection); //display the whole list of students
OleDbDataReader reader = readStudentCommand.ExecuteReader();
dataTable.Load(reader);
connection.Close();
return dataTable;
}
Here is the code that deletes an entry
private void MainDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
connection.ConnectionString = connectionString;
if (ConnectionState.Closed == connection.State)
{
connection.Open();
}
var senderGrid = (DataGridView)sender;
if (e.RowIndex >= 0 && senderGrid.Columns[e.ColumnIndex] == MainDataGridView.Columns["Delete"])
{
//this function retrieves the first column value of the deleted row, which has the ID of the entry (works with any table).
DeleteEntry(MainDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()); //exception thrown here (System.Windows.Forms.DataGridViewCell.Value.get returned null)
MainDataGridView.Rows.RemoveAt(e.RowIndex);
}
and here is DeleteEntry()
private void DeleteEntry(string deletedID)
{
string tableName = null;
string idType = null;
if (studentsDisplayed)
{
tableName = "Students";
idType = "Student ID";
}
else if(booksDisplayed)
{
tableName = "Books";
idType = "BookID";
}
else if(loansDisplayed)
{
tableName = "Loans";
idType = "Loan ID";
}
string deleteCommand = String.Format("DELETE * FROM {0} WHERE [{1}] = {2}", tableName, idType, deletedID);
OleDbCommand deleteEntryCommand = new OleDbCommand(deleteCommand, connection);
deleteEntryCommand.ExecuteNonQuery();
SaveData(); //this method just calls Update() in a dataAdapter of a relevant table
connection.Close();
}
Thank you!
Edit:
As per request, here is the code that switches the table. It simply references the first function and sets the returned dataTable as DataSource.
private void StudentButton_Click(object sender, EventArgs e) //display students
{
try
{
if (!studentsDisplayed)
{
MainDataGridView.DataSource = studentDAL.Read(); //studentDAL is the class that works with the Students table of my DB.
studentsDisplayed = true; //these 3 are to avoid duplicated creation of the same table
booksDisplayed = false;
loansDisplayed = false;
ComboBoxChanger(); //don't mind this, it's for an irrelevant feature
CreateButtons(5);
}
}
catch
{
throw;
}
}
Okay, so turns out the problem was the fact that DeleteEntry(MainDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString()) had a problem with the Cells[0] part. After the first time loading a table, the 0th cell just vanished. So, I rewrote the code so that instead of declaring tableName and idType in DeleteEntry(), they're declared in MainDataGridView_CellContentClick(), and then made the DeleteEntry() accept 3 idType and tableName as parameters, and changed the MainDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString() argument to MainDataGridView.Rows[e.RowIndex].Cells[idType].Value.ToString(). Now it works just fine!
I have a very basic question I want to update DataGridView using this code
private void updateDGV1_Click(object sender, EventArgs e)
{
SQLiteConnection sqliteCon = new SQLiteConnection(dbConnectionString);
// open connection to database
try
{
cmbl1 = new SQLiteCommandBuilder(datadp1);
datadp1.Update(ds1, "PlotDetails");
MessageBox.Show("Information Updated", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
load_table();
AutoCompleteSizeSearch();
AutoCompletePlotSearch();
AutoCompleteOwnerSearch();
AutoCompleteLocatoinSearch();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
After search for a result using this code
private void plots_txt_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(dt1);
dv.RowFilter = string.Format("D_ID LIKE '%{0}' AND Area LIKE '%{1}' AND Cat LIKE '%{2}' AND PBS LIKE '%{3}%' AND Name LIKE '%{4}%' AND Size LIKE '%{5}%' AND Location LIKE '%{6}%' AND PlotNo LIKE '%{7}%'", dids_combo.Text, areacs_txt.Text, categorycs_txt.Text, phblses_txt.Text, owners_txt.Text, sizes_txt.Text, locations_txt.Text, plots_txt.Text);
dataGridView1.DataSource = dv;
}
After getting result of search I couldn't been able to update searched result.
updateDGV1_Click works fine on the whole DGV but not on Searched result like in below image
After search,result not updating
I would actually recommend using the TableAdapter to communicate with your database instead of generating a connection in that fashion. This will also allow you to easily update your DataGridView with the contents of the TableAdpater Query (Search) that you want to preform. I wish I could go into more detail but I'm in a hurry at the moment I will provide links explaining this better below.
https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx
I personally use TableAdapters to connect databases in my projects, but I have found a solution that may also allow you to keep your code the way it is for the most part.
http://www.codeproject.com/Articles/14249/How-to-populate-DataGridView-GridView-with-SQL-sta
What you will need to do when you want to preform a search on the current working DataSet. This code is an example I haven't tested it.
string conn_str = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
string sql_str = “select * from table1”;
SqlDataAdapter data_adapter = new SqlDataAdapter(sql_str, conn_str);
SqlCommandBuilder cmd_builder = new SqlCommandBuilder(data_adapter);
// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
// This line populates our new table with the data from our sql query
data_adapter.Fill(table);
db_binding_source.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
data_grid_view.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
// you can make it grid readonly.
data_grid_view.ReadOnly = true;
// finally bind the data to the grid
data_grid_view.DataSource = db_binding_source;
Here is also another answer on SO similar to what you're asking
How do I Update/Reload DataGridView BindingSource?
I got a question for you guys.
How do I Dynamicly add an item to asp.net?
there a way to make a balloon looking box of text?
I know how to get items into ds from database and fill it up and read it for each row there is. but that does not help me alot when I want to make dynamicly some stuff and get a ballon view of text just like if you are looking at your phone and see the text messeges thats how I want it to look like.
I took a example of my code where I show how I fill the dataset and how I bind the data into a Gridview
DBControl.cs
public DataSet GetData(String queryString)
{
DataSet ds = new DataSet();
try
{
//run the query.
SqlDataAdapter adapter = new SqlDataAdapter(queryString, m_helpdeskconnection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch
{
// The connection failed. Display an error message.
//Message.Text = "Unable to connect to the database.";
}
return ds;
}
AdministrerBrugere.aspx.cs
DBControl db = new DBControl();
String queryString;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
queryString = "SELECT KundeNr, Navn FROM Kunder";
BindData();
}
}
private void BindData()
{
// Run the query and bind the resulting DataSet
// to the GridView control.
db.ConnOpenHelpdesk();
DataSet ds = db.GetData(queryString);
GridView1.DataSource = ds;
GridView1.DataBind();
db.ConnCloseHelpdesk();
}
You could use a DataRepeater to bind your content and use an ItemTemplate that has a CSS styled DIV to make it look like a baloon.
Try these links:
http://www.w3schools.com/css/css3_borders.asp
http://www.w3schools.com/aspnet/aspnet_repeater.asp
I am developing a program for a Computer Store using c# with VS2010 and Database Provider = OleDB.
I need a form for updating the existing Products information in the stock. So I have a DataGridView to show the products Table (Edit property = on)
My code for updating a row :
private void button1_Click(object sender, EventArgs e)
{
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow UpdateRow = dataGridView1.Rows[i];
if (UpdateRow.Selected == true)
{
try
{
com.CommandText = "UPDATE Products SET ProductName=#pname,Model=#model WHERE ProductID= " + UpdateRow.Cells[0].Value + "";
com.Connection = con;
com.Parameters.AddWithValue("#pname", UpdateRow.Cells[1].Value);
com.Parameters.AddWithValue("#model", UpdateRow.Cells[2].Value);
int count = com.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
con.Close();
}
That code works and it updates the access database file but it's only for one row (the selected row)
Now i want to update every edit the user have done in the DataGridView
So all i have to do is to delete the line if (UpdateRow.Selected == true) and that way , the loop will go for every row and update the info .
I debugged the program and it didn't crash but the Access database didn't update anything! I wonder why...
There are 2 methods to accomplish this:
Follow the dataset and datatable route, assign the datatable to the grid and then use the getchanges() method to retrieve the rows which have changed and then update the selected rows into the database
Use the following following function to capture the rowindex property of the changed row
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// use e.rowindex to get the row being modified and keep that in some list and
//after update button is pressed get the rows and update accordingly
//
}
I want to take the string from a text-box when the search button is pressed, then I want the row where that data grid is placed to be highlighted. I believe that this is possible. I don't know how this can be done. Please help me out.
string query = " SELECT * FROM suboffice where so_id like '%" + sor_id.Text + "%' ";
SqlConnection objConn = new SqlConnection(connectionString);
objConn.Open();
SqlDataAdapter subofficeTableAdapter1 =new SqlDataAdapter(query,objConn);
SqlCommandBuilder cBuilder = new SqlCommandBuilder(subofficeTableAdapter1);
DataTable dTable = new DataTable();
subofficeTableAdapter1.Fill(dTable);
dataGridView1.DataSource = dTable;
subofficeTableAdapter1.Update(dTable);
where sor is a search tab when ever i put any thing in this on run time my data grid view is updated. This program in to be made in c#
If you are using Windows Forms, here is a start. You may have to modify the code for your purposes if you are going to implement some sort of functionality such as "Find Next", "Find Previous", "Find All", etc.
The following is assuming you have a Button named SearchButton, a Textbox named SearchTextBox, and a DataGridView named MyDataGridView. The following code would be in the click event of your Search Button.
private void SearchButton_Click(object sender, EventArgs e)
{
MyDataGridView.ClearSelection(); //this will clear any currently selected cells
string searchstring = SearchTextBox.Text;
foreach (DataGridViewRow r in MyDataGridView.Rows)
foreach (DataGridViewCell c in r.Cells)
if (c.Value.ToString().Contains(searchstring))
{
r.Selected = true; //this will highlight the entire row
break; //if you want to "Select All" that are found, take this line out
}
}