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;
Related
I have datagridview with DataGridViewCheckBoxColumn i want to update the database if checkbox checked update the test_status to 5 , if check box not checked keep the test_status = 4 . the column name initial result.
I used the following code when click SAVE button:
private void btnSave_Click(object sender, EventArgs e)
{
int test_status = 4;
for (int i = 0; i < dgvResult.Rows.Count; i++)
{
foreach (DataGridViewRow row in dgvResult.Rows)
{
bool status = (bool)row.Cells[8].FormattedValue;
if (status)
{
test_status = 5;
}
else
{
test_status = 4;
}
}
result.UPDATE_LABORDERS_RESULTS(Convert.ToInt32(txtOrder.Text),txtExamUser.Text,
DateTime.Parse(DateTimeExamined.Value.ToString()),
Convert.ToInt32(dgvResult.Rows[i].Cells[2].Value),
dgvResult.Rows[i].Cells[4].Value.ToString(),
dgvResult.Rows[i].Cells[5].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[7].Value.ToString()),
Convert.ToInt32(txtPno.Text),
Convert.ToInt32(txtcustid.Text),
dgvResult.Rows[i].Cells[1].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[6].Value.ToString()),
Convert.ToInt32(txtUpdateCount.Text),test_status);
}
MessageBox.Show("Result Saved Successfully ", "Entering Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
what is the wrong with my code , what i need to update ?
UPDATE :
I debug the code its taking the value of last row only not each row , when i checked the box for last row in datagridview its updated all rows in the database and keep test status = 5 for all rows.
how to pass test_status from first foreach loop to second update_laborders_results?
You can update your database with test_status first for each row if checkbox checked to 5 then execute the other loop like this :
private void btnSave_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvResult.Rows.Count; i++)
{
foreach (DataGridViewRow row in dgvResult.Rows)
{
bool status = (bool)row.Cells[8].FormattedValue;
if (status)
{
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("UPDATE table set test_status = 5 // where condition ", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
result.UPDATE_LABORDERS_RESULTS(Convert.ToInt32(txtOrder.Text), txtExamUser.Text,
DateTime.Parse(DateTimeExamined.Value.ToString()),
Convert.ToInt32(dgvResult.Rows[i].Cells[3].Value),
dgvResult.Rows[i].Cells[5].Value.ToString(),
dgvResult.Rows[i].Cells[6].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[8].Value.ToString()),
Convert.ToInt32(txtPno.Text),
Convert.ToInt32(txtcustid.Text),
dgvResult.Rows[i].Cells[2].Value.ToString(),
Convert.ToInt32(dgvResult.Rows[i].Cells[7].Value.ToString()), Convert.ToInt32(txtUpdateCount.Text));
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 have two gridviews in my asp.net page. Where the datas are coming from two different databases. In that, one gridview has select row function. Now what I want to do is, I need to generate my 3rd gridview row by row according to the selection of the 1st gridview's 2 cells and the 2nd gridview 1st column data.(1st column data is common for all the rows).
The values in the gridview is showing as expected, But it will only hold one row data at a time. When I go ahead to select another value from the dropdownlist the gridview refreshes and the existing data will disappear and the new data appears.
How can I have the selected datas inserted row by row in a gridview?
Here are my code given below:
protected void btnAssign_Click(object sender, EventArgs e)
{
SetInitialRowToGrid();
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
DataRow tempRow = null;
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's Label values
var EmpID =
(Label)grdEmp.SelectedRow.FindControl("lblEmpID");
var firstName =
(Label)grdEmp.SelectedRow.FindControl("lblFirstName");
var date = DateTime.Now.ToString();
var planID =
(Label)grdPlanID.Rows[rowIndex].Cells[1].FindControl("lblPlanID");
// Create new row and update Row Number
tempRow = tempTable.NewRow();
tempTable.Rows[0]["Emp_ID"] = EmpID.Text;
tempTable.Rows[i - 1]["First_Name"] = firstName.Text;
tempTable.Rows[i - 1]["Created_Time"] = date;
tempTable.Rows[i - 1]["Plan_ID"] = planID.Text;
rowIndex++;
}
// Add data to datatable and viewstate
tempTable.Rows.Add(tempRow);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
grdList.DataSource = tempTable;
grdList.DataBind();
}
}
//Set Previous Data on Postbacks
SetPreviousData();
}
SetInitialRowToGrid() code is given below:
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("Emp_ID");
tempDataTable.Columns.Add("First_Name");
tempDataTable.Columns.Add("Created_Time");
tempDataTable.Columns.Add("Plan_ID");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
grdList.DataSource = tempDataTable;
grdList.DataBind();
}
SetPreviousData() code is given below:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 0; i < tempTable.Rows.Count; i++)
{
var EmpID =
(Label)grdEmp.SelectedRow.FindControl("lblEmpID");
var firstName =
(Label)grdEmp.SelectedRow.FindControl("lblFirstName");
var date = DateTime.Now.ToString();
var planID =
(Label)grdList.Rows[rowIndex].Cells[1].FindControl("lblPlanID");
EmpID.Text = tempTable.Rows[i]["Emp_ID"].ToString();
firstName.Text = tempTable.Rows[i]["First_Name"].ToString();
date = tempTable.Rows[i]["Created_Time"].ToString();
planID.Text = tempTable.Rows[i]["Plan_ID"].ToString();
rowIndex++;
}
}
}
}
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);
}
}
The gridview values is coming from excel sheet when the checkbox is checked i want those rows to be displayed into another gridview when the button is clicked
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Name of the Chemical "), new DataColumn("Grade"), new DataColumn("Quantity"), new DataColumn("Price in"), new DataColumn("Total") });
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = (row.Cells[0].FindControl("chkSelect") as CheckBox);
if (chkSelect.Checked)
{
string name = row.Cells[1].Text;
string grade = row.Cells[2].Text;
// int quantity = Convert.ToInt32((row.Cells[3].FindControl("Quantity") as TextBox));
//Decimal price = Convert.ToInt32(row.Cells[4].Text);
//Decimal price = Convert.ToDecimal(row.Cells[4]);
//Decimal total = Convert.ToDecimal(row.Cells[5]);
// Convert.ToInt32(GridView1.Rows[rowIndex].Cells[0].Text)
//string country = (row.Cells[2].FindControl("lblCountry") as Label).Text;
dt.Rows.Add(name, grade);
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
//gvSelected.DataSource = dt;
//gvSelected.DataBind();
}