Can't bind DataTable to GridView - c#

Hey guys I've just started programming and I'm running into a problem. The new Datatable i created doesnt show in GridView2 when button1 is clicked. Although it is filled with data from the "planning" table(checked that dtPlanning is filled with the TextBoxes in comment).
So in short: I want to get DataTable planning into the new DataTable dtPlanning and display it in a gridview.
Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dtPlanning = new DataTable();
dtPlanning.Columns.Add("Courseday", typeof(int));
dtPlanning.Columns.Add("Part", typeof(string));
dtPlanning.Columns.Add("Design", typeof(string));
dtPlanning.Columns.Add("Lesson", typeof(string));
//DataRow dr = planning.Rows[1];
//TextBox2.Text = (dr["Daynumber"]).ToString();
//TextBox3.Text = (dr["Part"]).ToString();
//TextBox4.Text = (dr["Design"]).ToString();
//TextBox5.Text = (dr["Lesson"]).ToString();
for (int i = 0; i < dtPlanning.Rows.Count; i++)
{
DataRow dr = dtPlanning.NewRow();
foreach (DataRow datarow in planning.Rows)
{
dtPlanning.Rows.Add(datarow);
}
}
GridView2.DataSource = dtPlanning;
GridView2.DataBind();
}
Source code:
<asp:GridView ID="GridView2" runat="server">
Thank you for your help.

Logically, dtPlanning.Rows.Count = 0 because this table is just initialized!
Secondly, you cannot Add a row from one table to another, user Import
for (int i = 0; i < planning.Rows.Count; i++)
{
dtPlanning.ImportRow(planning.Rows[i]);
}
I wonder why don't you just use the table planning?

You must:
Add to DataSet a new DataTable
Add to DataTable a new Columns
And GridView2.DataSource=YourNameDataSet.Tables[index_of_DataTable_in_DataSet].DefaultView;

Related

I have two datagridview, one on the staff calls, I want to make the other contain the number of staff did the call

The following images show my two datagrid views
From what I understand from your question, you can use the following method
public DataTable numOfCalls(DataTable table)
{
//Initialize Result Table
DataTable numOfCallsTable = new DataTable();
numOfCallsTable.Columns.Add("agentName", typeof(string));
numOfCallsTable.Columns.Add("numOfCall", typeof(int));
// Get the unique agents
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "agentName");
// Check if there are agents
if (distinctValues.Rows.Count > 0)
{
// Loop thru the agents
for (int i = 0; i < distinctValues.Rows.Count; i++)
{
string agentName = distinctValues.Rows[i]["agentName"].ToString();
// Get all the rows that this agent has
DataRow[] agentRows = table.Select($"agentName='{agentName}'");
// And then fill the second table
DataRow newRow = numOfCallsTable.NewRow();
newRow["agentName"] = agentName;
newRow["numOfCall"] = agentRows.Length;
numOfCallsTable.Rows.Add(newRow);
}
}
return numOfCallsTable;
}
You can call this method every time you add or delete a line to the first table.
update for the button that you asked
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
dataGridView2.DataSource = numOfCalls(dt);
}

How to dynamically delete rows in DataList c# asp

Looking for a way to dynamically delete rows from a datalist, providing a user a way to 'clean up' their input interface. The asp datalist gets loaded from SQL, then the user gets to manipulate the table before sending it on to another database.
I have a functioning 'addRows' by using a datatable session variable, adding rows to it then re-binding to the datalist, however I can't seem to get the same function with deleting rows.
Current logic is to use datalist 'delRows' command, get current typed-in or modified data from the asp datalist, assign it to a datatable, loop thru datatable and delete rows where certain fields are empty, then re-bind datatable to asp datalist.
Current code workup, but cannot get dt filled, error "dt = null" :
if (e.CommandName == "delRows")
{
DataList DataList1 = (DataList)FindControl("DataList1"); //find datalist in current state
Session["dataList1"] = DataList1; //assign datalist to session variable
DataTable dt = Session["dataList1"] as DataTable; //populate datatable with datalist session
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
string check = dr["item_no"].ToString();
if (check == String.Empty)
{
dr.Delete();
}
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
Hopefully there is a better way to accomplish this! Not to mention working....
For any future info seekers: Had to loop thru table to get most current textbox text into dt, then modify dt datatable in code behind, then rebind dt to datalist.
protected void doDataTable(string command, int e)
{
DataTable dt = new DataTable();
dt.Columns.Add("no", typeof(string));
dt.Columns.Add("desc", typeof(string));
dt.Columns.Add("code", typeof(string));
dt.Columns.Add("measure", typeof(string));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
foreach (DataListItem item in DataList4.Items)
{
string no = ((TextBox)item.FindControl("no")).Text;
string desc = ((TextBox)item.FindControl("desc")).Text;
string code = ((TextBox)item.FindControl("code")).Text;
string measure = ((TextBox)item.FindControl("measure")).Text;
int qty = Convert.ToInt16(((TextBox)item.FindControl("qty")).Text);
double price = Convert.ToDouble(((TextBox)item.FindControl("price")).Text.TrimStart('$'));
dt.Rows.Add(no, desc, code, measure, qty, price);
}
if (command == "add")
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
DataList4.DataSource = dt;
DataList4.DataBind();
}
else if (command == "del")
{
dt.Rows[e].Delete();
DataList4.DataSource = dt;
DataList4.DataBind();
}
}
Called with:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "addRow")
{
doDataTable("add", e.Item.ItemIndex);
}
if (e.CommandName == "delRows")
{
doDataTable("del", e.Item.ItemIndex);
}
}

How to add a row into datatable on button click event?

In Windows Forms, I want to add row by row into DataGridView on button click event by taking the values from other controls. I am using DataTable in this case and it is bound to DataGridView.
I am using the following code and it is working fine when the data is inserted for the first time. But my problem is when I click the button for the second time, the first row is overwritten with the second row of data.
private void btnAddToGrid_Click(object sender, EventArgs e)
{
LoadDataGridView();
}
private void LoadDataGridView()
{
dgvAdjustment.DataSource = GetAdjustmentTable();
}
private DataTable GetAdjustmentTable()
{
DataTable adjustmentTable = new DataTable();
DataColumn dataColumn;
dataColumn = new DataColumn("SourceOutletID", typeof(int));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("DestinationOutletID", typeof(int));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("TransactionDate", typeof(DateTime));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("MaterialName", typeof(string));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("AdjustmentType", typeof(int));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("CurrentBalance", typeof(decimal));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("AdjustmentQty", typeof(decimal));
adjustmentTable.Columns.Add(dataColumn);
dataColumn = new DataColumn("NewBalance", typeof(decimal));
adjustmentTable.Columns.Add(dataColumn);
DataRow dataRow = adjustmentTable.NewRow();
dataRow[0] = cmbSourceOutlet.SelectedValue;
dataRow[1] = cmbDestinationOutlet.SelectedValue;
dataRow[2] = TransDateTimePicker.Value;
dataRow[3] = cmbMaterialName.SelectedValue;
dataRow[4] = cmbAdjustmentType.SelectedValue;
dataRow[5] = Convert.ToDecimal(lblCurBalVal.Text);
dataRow[6] = Convert.ToDecimal(lblAdjVal.Text);
dataRow[7] = Convert.ToDecimal(lblNewQtyVal.Text);
int insertPosition = adjustmentTable.Rows.Count;
adjustmentTable.Rows.InsertAt(dataRow, insertPosition);
return adjustmentTable;
}
In ASP .NET applications, I use the session state to check whether DataTable is null by using the following code:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//Check if previous session is exist
if (Session["MyTable"] == null)
{
dtMyTable = new DataTable("MyTable");
dtMyTable.Columns.Add("Id", typeof(int));
dtMyTable.Columns.Add("LName", typeof(string));
}
else
{
//If yes then get it from current session
dtMyTable = (DataTable)Session["MyTable"];
}
//Add new row every time
DataRow dt_row;
dt_row = dtMyTable.NewRow();
dt_row["Id"] = TextBox1.Text;
dt_row["LName"] = TextBox2.Text;
dtMyTable.Rows.Add(dt_row);
//Update session table
Session["MyTable"] = dtMyTable;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
What can I do and how can I make the changes to get the right solution in Windows Forms? Any help will be much appreciated!
In GetAdjustmentTable, you are recreating adjustmentTable every time. So a new row will just overwrite the existing one.
You need to modify the code such that adjustmentTable is only created just once and subsequent calls add rows to it. One way to do that would be to make it a private field and to check if it's null, and create it if it is:
private DataTable _adjustmentTable;
private DataTable GetAdjustmentTable()
{
if (adjustmentTable == null)
{
adjustmentTable = new DataTable();
}
....

How to add new DataRow into DataTable?

I have a DataGridView binded to a DataTable (DataTable binded to database). I need to add a DataRow to the DataTable. I'm trying to use the following code:
dataGridViewPersons.BindingContext[table].EndCurrentEdit();
DataRow row = table.NewRow();
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
But it doesn't work, DataGridView has never been added a new row. Please, tell me, how can I fix my code?
Thank you in advance.
You can try with this code - based on Rows.Add method
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
Reference: https://learn.microsoft.com/dotnet/api/system.data.datarowcollection.add?view=net-5.0#System_Data_DataRowCollection_Add_System_Data_DataRow_
I found dotnetperls examples on DataRow very helpful. Code snippet for new DataTable from there:
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Weight", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Breed", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
return table;
}
//َCreating a new row with the structure of the table:
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
//Giving values to the columns of the row(this row is supposed to have 28 columns):
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
You have to add the row explicitly to the table
table.Rows.Add(row);
If need to copy from another table then need to copy structure first:
DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);
This works for me:
var table = new DataTable();
table.Rows.Add();
try table.Rows.add(row); after your for statement.
GRV.DataSource = Class1.DataTable;
GRV.DataBind();
Class1.GRV.Rows[e.RowIndex].Delete();
GRV.DataSource = Class1.DataTable;
GRV.DataBind();

Filling DataTable from GridView in C#

How can I fill DataTable from GridView in ASP.NET?
Simply, you can do like this:
BindingSource bindingSource = (BindingSource )yourGridView.DataSource;
DataTable yourDataTable= (DataTable ) bindingSource .DataSource;
Another way, you can do like this:
DataTable yourDataTable = yourGridView.DataSource as DataTable
I solved like this
if (myGridView.Rows.Count > 0)
{
var dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Columns.Add("Column2", typeof(Int64));
dt.Columns.Add("Column3", typeof(string));
foreach (GridViewRow row in gd_endYearSchool.Rows)
{
var id = row.Cells[1].Text;
//for find textbox
var tb1 = row.Cells[2].FindControl("tbNr") as TextBox;
int nrord = 0;
if (tb1 != null)
{
var ord = tb1.Text;
if (!Int64.TryParse(ord, out nrord))
{
nrord = 0;
}
}
var text=row.Cell[3].text;
dt.Rows.Add(id,nrord,text);
}
}
you can fill datatable from gridview with foreach
I'll do like this, i think this'll help u.
public void Data_table()
{
Session["Data"] = "";
DataTable dt = new DataTable();
//Add Columns to the datatable
dt.Columns.Add("c1");
dt.Columns.Add("c2");
dt.Columns.Add("c3");
//Define a datarow for the datatable dt
DataRow dr = dt.NewRow();
//Now add the datarow to the datatable
Session["Data"] = dt;
RadGrid1.DataSource = dt;
RadGrid1.Rebind();
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
if (((System.Data.DataTable)(Session["Data"])).Rows.Count.ToString() != "")
{
RadGrid1.DataSource = Session["Data"];
}
}
Thank you..,

Categories