gridview RowUpdating index - c#

When adding items to a gridview, I want the user to be able to select and edit/remove the item before writing the file (from the gridview entries) to a csv format. When I click on "edit" and update the information, I get an error. There is no row at position 0. (or whatever row you select to edit). Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
table = (DataTable)ViewState["table"];
ViewState["table"] = table;
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table;
//Bind data to the GridView control.
BindData();
}
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
}
public void CreateTable()
{
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
private void BindData()
{
griditems.DataSource = table;
griditems.DataBind();
}
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
////Somewhat works, doesn't update the part field with the text entered
//TextBox partedit = (TextBox)griditems.Rows[e.RowIndex].FindControl("Part");
//DataRow row = table.NewRow();
//row["Part"] = partedit;
//row["Quantity"] = qty;
//row["Ship-To"] = shipto;
//row["Requested Date"] = reqdate;
//row["Shipping Method"] = shipmthd;
//table.Rows.Add(row);
}
The commented out part that says "Somewhat works" will write blanks in the field updated when you click update.

The time you are adding data table in Session there is no row in it, thats why you get error "There is no row at position 0."
You are assigning table from viewstate to table it would be session.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
if(Session["table"] != null)
table = (DataTable)ViewState["table"];
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table; //This adds table without any record in it.
//Bind data to the GridView control.
BindData();
}
Add data table to session after you add records in datatable.
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
Session["table"] = table;
}
Update the Session["table"] in griditems_RowUpdating after updating.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
Session["table"] = dt;
}
Note: The way you are trying to get the updating recording is not appropriate you should read more about how to access data on row updating.

Related

how to filter a column in datagridview imported from excel file

For example I have a datagridview1 with data imported from a excel file and there are 12 columns: date, Name, Activity, Project,time, comment,ect. and 1000 row.
What I want to do is to filter only all with the Project name in project column.
for example I have support as a (Projectname) I want to show all columns filtyring by support rows.
I have combobox to select which column I need to filter it( e.g Project) here,
I tried with this code but it dose not work.
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string projektItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();
if (projektItem == "Project") {
foreach (DataRow dataRow in dataGridView1.Rows)
{
StringBuilder filter = new StringBuilder();
for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
{
filter.Append(dataRow[i].ToString());
filter.Append("\t");
}
dataGridView1.DataSource = filter.ToString();
}
if (projektItem == "Name") {
}
if (projektItem == "Aktivity") {
}
}
This is how I do it. convert datagridview to datatable
And this is func for filter purpose:
Hold the origin table to go back if you turn your filter off
//datagrid to datatable
DataTable datatable = new DataTable();
datatable = (DataTable)dataGridView1.DataSource;
//datatableOrigin to hold your origin table
DataTable originTable = null;
// find Function
Public void Find(string column, string st)
{
DataRow[] dtResult;
DataTable holder = New DataTable;
//get datatable Schema
DataTable holder = datatable.Clone();
holder.Rows.Clear();
If (originTable != null)
datatable = originTable;
Else
originTable = datatable;
//select return datarow array
dtResult = datatable.Select("[" + column + "] LIKE '%" + st + "%'");
//import all your result into holder
foreach(DataRow dr In dtResult){holder.ImportRow(dr);}
//pass from holder to datatable
datatable = holder.Copy();
holder.Clear();
}
public void showDT()
{
dataGridView1.DataSource = datatable;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// choose your column here
}
private void btn_Clicked(object sender, EventArgs e)
{
Find('YourColumn, 'your search string);
showDT();
}

How initialize dataset table that is not in a database?

I created a table in dataset that is not in a database, I need to set data to this table and bind data to a combobox, how can I do this?
DataRowView drv = statusBindingSource.AddNew() as DataRowView;
drv.Row["Value"] = 1;
drv.Row["Name"] = "Active";
statusBindingSource.EndEdit();
statusBindingSource.Add(drv);
I cannot add external objects to this list.
The new DataTable is created, filled with data and bound to the combo box. I did not include a DataSet or BindingSource.
private void Form1_Load(object sender, EventArgs e)
{
CreateDataTable();
cbo1.SelectedIndex = -1;
}
private void CreateDataTable()
{
//Create new DataTable
DataTable dt = new DataTable();
//Add colums with column name and datatype
dt.Columns.Add("Value", Type.GetType("System.Int32"));
dt.Columns.Add("Name", Type.GetType("System.String"));
//Add data
object[] data = { 1, "Active" };
dt.Rows.Add(data);
object[] data2 = { 2, "Passive" };
dt.Rows.Add(data2);
//Bind to combo box
cbo1.DataSource = dt;
cbo1.DisplayMember = "Name";
cbo1.ValueMember = "Value";
}
private void Cbo1_SelectionChangeCommitted(object sender, EventArgs e)
{
MessageBox.Show($"The display member is {((DataRowView)cbo1.SelectedItem)["Name"]}, The value member is {cbo1.SelectedValue}");
}

bind asp.net gridview column form textbox value dynamically

I want to bind gridview column from textbox value for example: I have two textbox and a button what i exactly want that i will give input in the two textboxes and when i clicked the button the textbox values will show in gridviw and want to do this for multiple times without replacing the previous values.
I found so many relevant answer but all are done with hard code inside button click event
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name",
typeof(string)),
new DataColumn("Age", typeof(decimal)) });
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind()
}
which replace the previous values when i insert new values, but i want to keep all the previous values in which I stuck .thanks
this code will help you to get current data from gridview to datatable
and then you can append new rows accordingly .
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt =GetGridData();
dr = dt.NewRow();
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
}
private DataTable GetGridData ()
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
return _dataTable;
}
You can store the values from each PostBack into a Session or ViewState, otherwise you'll lose all the data when the button is clicked again.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt;
//check if the datatable already exists in the viewstate, if not create a new datatable
if (ViewState["myTable"] == null)
{
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name", typeof(string)), new DataColumn("Age", typeof(decimal)) });
}
else
{
//correct viewstate exists, cast back to a datatable
dt = ViewState["myTable"] as DataTable;
}
//add the new values
dt.Rows.Add(TextBox1.Text, Convert.ToDecimal(TextBox2.Text));
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//save the datatable into the viewstate
ViewState["myTable"] = dt;
//clear the textboxes
TextBox1.Text = "";
TextBox2.Text = "";
}

How to put the data from the textbox into the empty rows of grid

I want to show 16 empty rows in a gridview of asp.net. I have a button and textbox outside the grid, on a button click, I have to insert the data from the textbox into the grid but the problem is that the data inserted after the 16 rows. How the data will be inserted in empty rows first.?
I bound the datasource with null but the grid is not visible so i create the rows on pageload event..
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtSource = new DataTable();
dtSource.Columns.Add("DateTime");
dtSource.Columns.Add("Detail");
dtSource.Columns.Add("Status");
dtSource.Columns.Add("Cancel");
for (int i = 0; i <= 15; i++)
{
dtSource.Rows.Add("", " ", " ", " ");
}
ViewState["dtSource"] = dtSource;
gridItem.DataSource = dtSource;
gridItem.DataBind();
}
}
and here is the code for the button
protected void btnAdd(object sender, EventArgs e)
{
DataTable dtSource = ViewState["dtSource"] as DataTable;
DataRow dr = dtSource.NewRow();
dtSource.Rows.Add(DateTime.Now, itemDetail, "", "");
gridItem.DataSource = dtSource;
gridItem.DataBind();
ViewState["dtSource"] = dtSource;
}
That's because you are creating a new row and adding it like below
DataRow dr = dtSource.NewRow();
There is no point in adding those 16 rows. You should rather do something like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtSource = new DataTable();
dtSource.Columns.Add("DateTime");
dtSource.Columns.Add("Detail");
dtSource.Columns.Add("Status");
dtSource.Columns.Add("Cancel");
ViewState["dtSource"] = dtSource;
gridItem.DataSource = dtSource;
gridItem.DataBind();
}
}
protected void btnAdd(object sender, EventArgs e)
{
DataTable dtSource = ViewState["dtSource"] as DataTable;
DataRow dr = dtSource.NewRow();
dtSource.Rows.Add(DateTime.Now, itemDetail, "", "");
gridItem.DataSource = dtSource;
gridItem.DataBind();
ViewState["dtSource"] = dtSource;
}

How to write every time to a new row of data table?

How can i insert each time a diffrent row in datatable?
The data table is used in a dataGridView to write a log. I need each time to write in a diffrent line (row) in the datatable, when I can't know how many rows I need in runtime.
Another thing; the datatable is loaded from a XML file, so there might be already rows in the data table.
What can i do? (in short, I always write in the same row) in C#
EDIT:
here is the code:
From some reason, the DateGridView isonly having one row(This is a method that activated in a click of a button)
public void gridStart(string i, string b, string c)
{
DataTable dt = new DataTable();//empty table with no schema
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
}
You should be able to Use DataTable.NewRow(). There are several samples on that MSDN page. If you have more questions please provide some sample code to your answer.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = MyDataTable;
}
private string _fileName = "MyCache.xml";
private DataTable _myDataTable;
public DataTable MyDataTable
{
get
{
if (_myDataTable == null)
{
_myDataTable = new DataTable();
if (File.Exists(_fileName))
_myDataTable.ReadXml(_fileName);
else
InitDataTable(_myDataTable);
}
return _myDataTable;
}
}
private void InitDataTable(DataTable table)
{
table.TableName = "MyTable";
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Caller", typeof(string));
table.Columns.Add("Result", typeof(string));
}
// Have your add code call this method!
private void AddValue(DateTime date, string caller, string result)
{
var row = MyDataTable.NewRow();
row["Date"] = date;
row["Caller"] = caller;
row["Result"] = result;
MyDataTable.Rows.Add(row);
}
protected override void OnClosed(EventArgs e)
{
if (_myDataTable != null)
_myDataTable.WriteXml(_fileName, XmlWriteMode.WriteSchema);
base.OnClosed(e);
}
If it is bound to a data source, you need to first get the data source,
// Assuming it's a DataTable
DataTable dt = ((DataTable)myDataGridView.DataSource);
insert rows to your data source (like what your method is doing in your post), then tell the view to refresh its contents.
So maybe something like this would work:
public void gridStart()
{
DataTable dt = new DataTable();
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
dataGridView1.DataSource = dt;
// Call method to insert values.
}
to start up the grid, and:
public void gridInsert(string i, string b, string c)
{
DataTable dt = (DataTable)myDataGridView.DataSource;
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
// Call another method to refresh grid view.
}
to call when you want to insert data to your DataTable.
My solution:
public partial class _Default : System.Web.UI.Page
{
DataTable tb = new DataTable();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
DataTable dt = new DataTable("table");
dt.Columns.Add(new DataColumn("NR", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Dihname", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("ing", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Cost", Type.GetType("System.String")));
Session["ss"] = dt;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
tb = (DataTable)Session["ss"];
DataRow r1 = tb.NewRow();
r1[0] = ViewState["dishid"].ToString();
r1[1] = ViewState["dishname"];
r1[3] = Label3.Text;
tb.Rows.Add(r1);
DataList5.DataSource = tb;
DataList5.DataBind();
}
}

Categories

Resources