Fill DataGridView in C# with Oracle? - c#

I am using C# asp.net, I have a class that return an ArrayList from the database. When the user presses a button on the page. So, is there is a way to fill it? Right now I am trying to find a datagridview.

Here is an example
Source : http://www.etechpulse.com/2012/10/bind-array-list-elements-to-grid-view.html
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// Single Dimensional array
private void BindGridview()
{
string[] arrlist = // your function that gets the arraylist
DataTable dt = new DataTable();
// you need to do the following for each column
dt.Columns.Add("Name");
for (int i = 0; i < arrlist.Count(); i++)
{
dt.Rows.Add();
dt.Rows[i]["Name"] = arrlist[i].ToString();
}
gvarray.DataSource = dt; //gvarray is your GridView defined in aspx design
gvarray.DataBind();
}
Also do not forget to add AutoGenerateColumns="false" if you want to fill the grid programmatically.

Related

Updating DataGridView Selected Rows

I tried to update selected rows in DataGridView, but the result is strange, it always missing a row or another. The problem is when I click btnSettled button to set the settled date, then click btnUpdate to update the database, the result seems ok, but after click btnRefresh to refresh the DGV, there is always a missing row. Is that the problem on UpdateCommand or foreach loop? Please help me to solve this problem. Thank you.
before click btnSettle
after click btnSettled and btnUpdate
after click btnRefresh
My code as follows:
DataTable dtTrx = new DataTable();
SqlDataAdapter daTrx = new SqlDataAdapter();
DataSet dsTrx = new DataSet();
public Form1()
{
InitializeComponent();
getData();
}
private void getData()
{
string strConn = "Data Source=.\\xpw;Initial Catalog=MyStock;Integrated Security=True;";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string sqlTrx = "SELECT TrxID, TrxDate,Ticker,Qty,Price,Type,AccID, SettledDate,BrokerUserID FROM Trx";
daTrx = new SqlDataAdapter(sqlTrx, conn);
SqlCommandBuilder cbTrx = new SqlCommandBuilder(daTrx);
daTrx.Fill(dsTrx, "trx");
conn.Close();
dtTrx = dsTrx.Tables["trx"];
dgvTrx.DataSource = dtTrx;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
daTrx.Update(dsTrx, "trx");
}
private void btnRefresh_Click(object sender, EventArgs e)
{
dsTrx.Clear();
daTrx.Fill(dsTrx, "trx");
}
private void btnSettled_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell c in dgvTrx.SelectedCells)
{
dgvTrx[7, c.RowIndex].Value = "2017/7/23";
}
}
First of all you need start using parameterized SQL queries.
Secondly I don't see a problem with your code, but you try this :
private void btnSettled_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow r in dgvTrx.SelectedRows)
{
r.Cells["SettledDate"].Value = "2017/7/23"; //use the column name instead of column index
}
this.BindingContext[dgvTrx.DataSource].EndCurrentEdit();
//the above line is added to improve the solution
//as per the link mentioned in the accepted answer
}
The reason behind this approach is that now even if you change the column position, you won't have to re-write the code to match the changes
As you are using SelectedCells, thus unless your mouse is dragged over to the last Cell it won't be added in the SelectedCell collection
Note: in r.Cells["SettledDate"].Value I assumed the column name is SettledDate
Finally I found the solution in :
Programmingly udpating selected rows misses the last one in dgv.DataSource.GetChanges()?
It only needs to end-edit the last row after foreach loop:
this.BindingContext[dgvTrx.DataSource].EndCurrentEdit();
Thanks again to #Nobody.

columns: Datagridview to Datatable

I am facing this issue, I have datagridview and a datatable.
VPfn_CreateDataGrid();//This fuction creates gridview columns
DataTable invoice_table = (DataTable)invoice_data.DataSource;
now First thing, datagridview is empty when form loads. What I am trying to do is adding data to datagridview via multiple textboxes and combomoxes and for that I am using datatable.
private void btn_add_Click(object sender, EventArgs e)
{
DataRow x = invoice_table.NewRow();
x["serial_number"] = tsr.Text.ToString();
x["item"] = combo_items.SelectedItem.ToString();
x["item_rate"] = tr.Text;
x["item_qty"] = tq.Text;
x["item_unit"] = combo_unit.SelectedItem.ToString();
x["item_vat"] = combo_vat.SelectedItem.ToString();
x["amount"] = ta.Text;
invoice_table.Rows.Add(x);
invoice_data.Refresh();
}
And the error is "Column 'serial_number' does not belong to table"
first you have to create a the data table with the specific column. while your datagridview is empty the DataTable also will be empty.
DataTable invoice_table = (DataTable)invoice_data.DataSource;
infront of this..
while loading your form you can create datatable with the columns.
DataTable invoice_table; //Global
private void load()
{
invoice_table = new DataTable();
invoice_table.Columns.Add("serial_number", typeof(int));
invoice_table.Columns.Add("item");
.....
}
after that
private void btn_add_Click(object sender, EventArgs e)
{
DataRow x = invoice_table.NewRow();
x["serial_number"] = tsr.Text.ToString();
x["item"] = combo_items.SelectedItem.ToString();
x["item_rate"] = tr.Text;
x["item_qty"] = tq.Text;
x["item_unit"] = combo_unit.SelectedItem.ToString();
x["item_vat"] = combo_vat.SelectedItem.ToString();
x["amount"] = ta.Text;
invoice_table.Rows.Add(x);
invoice_data.Refresh();
}
Try this...

Dynamically add rows to DataTable

I have an asp.net form with a textbox and a button. Each time the button is clicked I need the text from the textbox to be added as a new row in a table, which will then be presented on a gridview.
I have managed to add the text from the textbox as a new row, but every time I click the button it seems the table is not saved (meaning - I end up with only one row).
public partial class buildTable : System.Web.UI.Page
{
DataTable dt = new DataTable();
public int namesCounter;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ID", typeof(Int16));
dt.Columns.Add("name", typeof(string));
namesCounter = 0;
names_GV.DataSource = dt;
}
protected void addName_Click(object sender, EventArgs e)
{
namesCounter += 1;
DataRow dtrow = dt.NewRow();
dtrow["ID"] = namesCounter;
dtrow["name"] = newName_TXT.Text;
dt.Rows.Add(dtrow);
names_GV.DataBind();
}
}
I'm guessing this has something to do with postback...
The problem here lies in the "statelessness" of asp.net. In short, each round trip to the page (first visit, post-backs) creates a new instance of buildTable, thus re-instantiating your dt variable and setting it as data source to your grid.
Consider sending the user input to some sort of persistence layer that enables you to hold the data per-user and rebinding said data with each post back. The strategy which could be used here really depends on the size and context of your application.
Please refer to:
Microsoft's ASP.NET State Management Overview (http://msdn.microsoft.com/en-us/library/75x4ha6s(v=vs.100).aspx) for state management strategies
Microsoft's State Management Recommendations (http://msdn.microsoft.com/en-us/library/z1hkazw7(v=vs.100).aspx) for state management recommendations
Introduction to ASP.NET Web Pages (http://msdn.microsoft.com/en-us/library/ms178125(v=vs.100).aspx) for further details about the page lifetime
You need to Add the ID and Table to Viewstate so that the State is retained because, here we are not saving the Data in the Database. So every time the Page Loads, the Data is Null unless we save it in a viewstate.
Check with the Code below:-
It will run perfectly :-
DataTable dt = new DataTable();
public int namesCounter;
protected void Page_Load(object sender, EventArgs e)
{
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("name", typeof(string));
//namesCounter = 0;
if (!IsPostBack)
{
ViewState["Number"] = 0;
ViewState["table"] = dt;
}
names_GV.DataSource = dt;
names_GV.DataBind();
}
protected void addName_Click(object sender, EventArgs e)
{
dt = (DataTable)ViewState["table"];
namesCounter = Convert.ToInt32(ViewState["Number"]) + 1;
ViewState["Number"] = namesCounter;
DataRow dtrow = dt.NewRow();
dtrow[0] = namesCounter;
// dtrow["ID"] = namesCounter;
dtrow["name"] = newName_TXT.Text;
dt.Rows.Add(dtrow);
ViewState["table"] = dt;
names_GV.DataSource = dt;
names_GV.DataBind();
}
This code is working properly with me,
add them in button click event
:
DataTable dt_items = new DataTable();
dt_items.Columns.Add("Item");
dt_items.Columns.Add("Quantity");
if (grid_items.Rows.Count > 0)
{
foreach (GridViewRow row in grid_items.Rows)
{
dt_items.Rows.Add(row.Cells[0].Text,row.Cells[1].Text);
}
}
dt_items.Rows.Add(ddl_item.SelectedItem.Text, txt_itemAmount.Text);
grid_items.DataSource = dt_items;
grid_items.DataBind();

Format GridView Auto Generated Columns

I am trying to format the width of my gridview columns dynamically for easy of use in editing and updating. Is it possible to have multiple column widths defined? Here is the code I am using to create the gridview...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create a new table.
DataTable taskTable = new DataTable("TaskList");
// Create the columns.
taskTable.Columns.Add("Id", typeof(int));
taskTable.Columns.Add("Description", typeof(string));
taskTable.Columns.Add("IsComplete", typeof(bool));
//Add data to the new table. - could fill the table from database query if desired
for (int i = 0; i < 1; i++)
{
DataRow tableRow = taskTable.NewRow();
//tableRow["Id"] = 0;
tableRow["Description"] = "";
tableRow["IsComplete"] = false;
taskTable.Rows.Add(tableRow);
}
//Persist the table in the Session object.
Session["TaskTable"] = taskTable;
//Bind data to the GridView control.
BindData();
}
}
Is it possible to make a statement like:
taskTable.Column.Add("Id", typeof(int), width="200px");???
First you must change AutoSizeColumnsMode set to fill then you can change the width of the column.
dataGridView1.Columns[columnName].AutoSizeMode= DataGridViewAutoSizeColumnMode.None;
dataGridView1.Columns[columnName].Width = columnWidth;

Persisting DataTable or GridView DataSource

I have a Click Event that fills a DataTable and the DataTable is the source of my GridView.
Then I have another click event that tries to get the GridView DataSource e converts it back to a DataTable Like:
DataTable dt = (DataTable)GridView1.DataSource;
But the Datasource returns null. Event if I put the code and the Page_Init event waiting for the right postBack
so I would like to know how can i persist the datasource of the gridview, or the DataTable
edited as required:
here is the whole code:
ps: the Page_Init was another try to get the datasource
private DataTable _dataTable;
public DataTable dataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string ctrlname = BLL.Common.GetPostBackControlId(this.Page);
if(ctrlname == "ButtonDownload")
{
DataTable dt = (DataTable)GridView1.DataSource;
}
}
}
protected void Filter_Click(object sender, EventArgs e)
{
string[] status = new string[2];
status[0] = "Paga";
status[1] = "Disponivél";
dataTable = BLL.PagSeguro.GetTransactions(TextBoxInicio.Text, TextBoxFim.Text, status);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void GetDataSource(object sender, EventArgs e)
{
DataTable dt = (DataTable)GridView1.DataSource;
}
This might work for you.
public partial class Demo : System.Web.UI.Page
{
private DataTable _myData = null;
protected DataTable MyData
{
get
{
if (null == _myData)
{
// You would load your data here.
_myData = new DataTable();
}
return _myData;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Lets say you set your data source here
myGrid.DataSource = this.MyData;
}
protected void Rendering(object sender, EventArgs e)
{
// This is some other event that also needs to get at the data.
DataTable mydata = this.MyData;
}
protected void Unload(object sender, EventArgs e)
{
if (null != _myData)
{
_myData.Dispose();
_myData = null;
}
}
I'm pretty sure you can only access the datasource that way through the DataBound event or ItemDataBound event. You might be able to access the DataRowView for each item in the Items collection, but I'm not sure:
DataRow row = ((DataRowView)GridView1.Rows[0].DataItem).Row;
As for persisting the datasource, you need to consider whether that's a good idea. Your options for storing the datasource are Session or Cache, but if the result set is fairly small it might be more efficient to make another round trip when you need the datasource. Whatever you decide to do, don't store it in ViewState.

Categories