I have a datatable that I am populating with data, however if I want to edit the row I am getting an error
Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
The code that populates the gridview is
public void addTochkout(string type, string no)
{
DataTable dt = (DataTable)Session["table_chkout"];
DataRow dr = dt.NewRow();
dr[0] = type;
dr[1] = no;
dt.Rows.Add(dr);
Session["table_detail"] = dt; //save dt to new session
gridbind();
}
public void gridbind()
{
//gridview
if (Session["table_detail"] != null)
{
DataTable dt = (DataTable)Session["table_detail"];
if (dt.Rows.Count > 0)
{
chkoutDetail.DataSource = dt;
chkoutDetail.DataBind();
string countitems = dt.Rows.Count.ToString();
Session["cart_counter"] = countitems;
}
}
else
{
chkoutDetail.DataSource = null;
chkoutDetail.DataBind();
}
}
Now, when I try and update the gridview I am getting the error above from the line
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
The entire code block where is erroring is
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
//Update the values.
GridViewRow row = chkoutDetail.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Price"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
//Reset the edit index.
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
}
I would be very grateful if you could help me solve this issue.
Simon
Note that when you have the Edit option enabled, the first and second cells of the edit mode of the row in the grid view are linkbuttons(Update and Cancel). So probably you have to change the index while getting the textbox in the row
//Cell number 2 for the first textbox. 0 for update link and 1 for cancel link
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
I had figured out my issue just after posting the, but it wouldn't allow me to answer the question.
heres my solutions
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
// //Update the values.
string type = e.NewValues[0].ToString();
string qty = e.NewValues[1].ToString();
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
dt.Rows[e.RowIndex]["TicketType"] = type;
dt.Rows[e.RowIndex]["TicketNo"] = qty;
dt.AcceptChanges();
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
int value1 = Convert.ToInt32(ddtickettype.SelectedItem.Value);
int value2 = Convert.ToInt32(ddTicketno.SelectedItem.Value);
string tType = ddtickettype.SelectedItem.Text;
string tNo = ddTicketno.SelectedItem.Text;
int prevTotal = Convert.ToInt32(lblAmount.Text);
int total = (value1 * value2) + prevTotal;
Session["TotalAmount"] = total.ToString();
if (Session["TotalAmount"] != null)
{
lblAmount.Text = Session["TotalAmount"].ToString();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
Related
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();
}
Good day!
Please help me on my concern. I have a code here which allows to add rows to the datagridview I created named dgvSchedule. I want to transfer data from the other datagridview dgvCalendar by double clicking the data in the cell. My problem is I can only add data on the first row in dgvSchedule and the next rows are empty.
I have attached screenshot also of my application.
Thank you.
private void dgvCalendar_DoubleClick(object sender, EventArgs e)
{
if (cmbTimeSched.Text != "")
{
string yearnow = DateTime.Now.Year.ToString();
int year = Convert.ToInt32(yearnow);
int rowIndex = dgvCalendar.CurrentCell.RowIndex;
int colIndex = dgvCalendar.CurrentCell.ColumnIndex;
if (dgvCalendar.Columns[colIndex].HeaderText != "SUN")
{
string Daynum = dgvCalendar.Rows[rowIndex].Cells[colIndex].Value.ToString();
int dayNum = Convert.ToInt32(Daynum);
int num = DateTime.Parse("" + selectMonths.Text + year).Month;
DateTime dateSelected = new DateTime(year, num, dayNum);
dgvSchedule.Rows.Add();
dgvSchedule.Rows[0].Cells[0].Value = lblIDNum.Text;
dgvSchedule.Rows[0].Cells[1].Value = cmbTimeSched.Text;
dgvSchedule.Rows[0].Cells[2].Value = dgvCalendar.Columns[colIndex].HeaderText.ToString();
dgvSchedule.Rows[0].Cells[3].Value = dateSelected.ToString("MM/dd/yyyy");
}
else
{ MessageBox.Show("You selected a date that is on SUNDAY!"); }
}
else
{ MessageBox.Show("PLEASE SELECT TIME SCHEDULE FIRST!"); }
}
MyApplication:
Because you are specifically saying to fill the record at Row[0] in dgvSchedule table.
int count=dgvSchedule.Rows.Count;
dgvSchedule.Rows[count+1].Cells[0].Value = lblIDNum.Text;
dgvSchedule.Rows[count+1].Cells[1].Value = cmbTimeSched.Text;
dgvSchedule.Rows[count+1].Cells[2].Value=
dgvCalendar.Columns[colIndex].HeaderText.ToString();
dgvSchedule.Rows[count+1].Cells[3].Value = dateSelected.ToString("MM/dd/yyyy");
My other suggestion is you can use dataset to fill the grid.
DataTable dt1 = new DataTable();
//remove all the rows of table
while (dgvSchedule.Rows.Count > 1)
{
dgvSchedule.Rows.RemoveAt(0);
}
//fill the table with updated records
cnn.Open();
MySqlDataAdapter adp = new MySqlDataAdapter("query for fetch the results from data base which you need to fill in the table", cnn);
adp.Fill(dt1);
dgvSchedule.DataSource = dt1;
adp.Dispose();
cnn.Close();
Through Edit link button I'm able to edit record using code below . As you can see here number of columns are 4 , for fixed column number this code is fine but In my condition Column numbers are not fixed ,they may 4 or may be 5 for next insert. How can I get column names and create that number of string variable, so that I can assign string values to particular field ?
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string a = (row.Cells[3].Controls[0] as TextBox).Text;
string b = (row.Cells[4].Controls[0] as TextBox).Text;
string c = (row.Cells[5].Controls[0] as TextBox).Text;
string d = (row.Cells[6].Controls[0] as TextBox).Text;
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[row.RowIndex]["Column0"] = a;
dt.Rows[row.RowIndex]["Column1"] = b;
dt.Rows[row.RowIndex]["Column2"] = c;
dt.Rows[row.RowIndex]["Column3"] = d;
ViewState["dt"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
btnGetSelected.Visible = true;
}
Do you mean you need the columns names of the GridView?
You could use either of these
gv.HeaderRow.Cells[i].Text
gv.Rows[0].Cells[i].Text
Reference
It you want column names of DataTable use
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
This worked for me.
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
DataTable dt = ViewState["dt"] as DataTable;
int j=0;
for (int i = 3; i < row.Cells.Count; i++)
{
string a = (row.Cells[i].Controls[0] as TextBox).Text;
dt.Rows[row.RowIndex][j] = a;
j++;
}
ViewState["dt"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
btnGetSelected.Visible = true;
}
I'm creating website in Asp.net (Framework 4.0).
In this website I have taken a Gridview which is filled with data on page load.
Now I'm trying to Insert data from Gridview to database on button click. While inserting into database GridView Cells shows blank values.
Code as follows for GridView Binding
void BindGrid()
{
GridView1.DataSource = obj3.GetCart(sid, uid);
GridView1.DataBind();
int rowCount = GridView1.Rows.Count;
if (rowCount == 0)
{
GridView1.Visible = false;
lblCartCount.Visible = true;
lblCartCount.Text = " No Items In Cart";
}
else
{
GridView1.Visible = true;
GridView1.FooterRow.Cells[3].Text = "Total Price";
GridView1.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Right;
GridView1.FooterRow.Cells[9].Text = totals.ToString();
totprice = Convert.ToInt32(totals.ToString());
totals = 0;
lblCartCount.Visible = false;
}
}
Code for Insert button click for Insert data from Gridview to database.
protected void btnOrderNow_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
BindGrid();
val1 = obj4.AddOrderItem(orderid, Convert.ToInt32(g1.Cells[2].Text),
Convert.ToInt32(g1.Cells[5].Text), Convert.ToInt32(g1.Cells[4].Text),
Convert.ToInt32(g1.Cells[6].Text), Convert.ToInt32(g1.Cells[7].Text),
g1.Cells[0].Text, Convert.ToInt32(g1.Cells[1].Text));
}
}
I found my answer by myself. The code for Insert data from Gridview to database has some following changes .
protected void btnOrderNow_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
string sss = (((Label)(g1.Cells[g1.RowIndex].FindControl("lblSession"))).Text.Trim());
int uuu = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("Label5"))).Text.Trim());
int itemid = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblItemId"))).Text.Trim());
int priceid = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblPriceId"))).Text.Trim());
int quantity = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblItemQuantity"))).Text.Trim());
int price = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblPrice"))).Text.Trim());
int bprice = int.Parse(((Label)(g1.Cells[g1.RowIndex].FindControl("lblBulkPrice"))).Text.Trim());
val2 = obj4.OrderTempCartUpdate(sss, uuu);
}
}
In this instead of taking only g1.Cells[0].text wasn't able to find particular row index . So I have added
(((Label)(g1.cells[g1.RowIndex].FindControl("LabelName"))).
instead of g1.Cells[0].text;
I have a winforms application that I am developing, I have hit a dead end. What I am trying to do is on each "click", add a new row to my DataTable with the values input in the form. This Datatable is the DataSource for my DataGridView. Can someone point me in the right direction on how this can be achieved.
Articles I looked at:
How to add new row to datatable gridview
My code:
private void btnAdd_Click(object sender, EventArgs e)
{
//inserting into order table
DataTable dt = new DataTable();
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
On each click you are creating a new DataTable which would be with just one row, You need to create DataTable once and then just keep adding rows to in the click. Define your DataTable at class level and then in your event just add a new row to it.
DataTable dt = new DataTable(); //at class level
private void Form1_Load(object sender, EventArgs e)
{
CreateDataTableColumns();
//.... your code
}
Then have a method to create table structure, call that method once from your From_Load event.
private void CreateDataTableColumns()
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
}
Later add rows to your class level DataTable in Add event.
private void btnAdd_Click(object sender, EventArgs e)
{
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
(I believe you are doing something with the exception object in your catch block, like logging, showing message to user etc)