I am creating a datatable and adding rows dynamically and am binding datatable to gridview when there are no records am displaying as no records found using emptydatatext but this is not working.Here is my code
protected void show_fence_report(object sender, EventArgs e)
{
int drp_fence_id = common.make_int(common.get_request("drp_fence"));
string fence_start_date_time1 = common.get_request("fence_start_date_time");
string fence_end_date_time1 = common.get_request("fence_end_date_time");
//Delete data from datatable and gridview
dt_fence.Clear();
if (gridview_fence.DataSource != null)
{
((DataView)gridview_fence.DataSource).Table.Clear();
}
gridview_fence.DataBind();
gridview_fence.EmptyDataText = "Records Not Found";
hid_fence_id.Value = drp_fence_id.ToString();
hid_fence_start_datetime.Value = fence_start_date_time1;
hid_fence_end_datetime.Value = fence_end_date_time1;
display_fence_report();
gridview_fence.EmptyDataText = "Records Not Found";
}
public void display_fence_report()
{
string fence_id1 = "", fence_name1, fence_type1 = "", fence_status;
float default_size = 100000, landmark_latitude1 = 0, landmark_longitude1 = 0, fence_latitude1 = 0, fence_longitude1 = 0, fence_size1 = 0, longitude_x = 0, latitude_y = 0;
int points_polygon = 0;
ArrayList vertices_x = new ArrayList();
ArrayList vertices_y = new ArrayList();
query = "select latitude,longitude,added_date_time,speed,location,(select object_value from tracking_master_objects where object_id = a.object_id) as object from tracking_data_domain a where object_id in(select object_id from tracking_assign_fence a where fence_id = '" + hid_fence_id.Value + "' and is_active = '1') and (added_date_time between convert(datetime, '" + hid_fence_start_datetime.Value + "', 105) and convert(datetime, '" + hid_fence_end_datetime.Value + "', 105)) order by gps_id asc";
dr = common.run_query(query, db, cm, dr, 0);
if (dr.HasRows)
{
//To Build Fence Latitudes and Longitudes
query = "select fence_id,fence_name,fence_type,landmark_latitude,landmark_longitude,fence_latitude,fence_longitude,fence_size from tracking_master_fences where domain_id = '" + domain_id1 + "' and fence_id = '" + hid_fence_id.Value + "' and is_active = '1'";
dr2 = common.get_row(query, db2, cm2, dr2, 0);
if (dr2.HasRows)
{
fence_id1 = dr2["fence_id"].ToString();
fence_name1 = dr2["fence_name"].ToString();
fence_type1 = dr2["fence_type"].ToString();
landmark_latitude1 = common.make_float(dr2["landmark_latitude"].ToString());//fs_lat
landmark_longitude1 = common.make_float(dr2["landmark_longitude"].ToString());//fs_long
fence_latitude1 = common.make_float(dr2["fence_latitude"].ToString());//sec_lat
fence_longitude1 = common.make_float(dr2["fence_longitude"].ToString());//sec_long
fence_size1 = common.make_float(dr2["fence_size"].ToString());
}
dr2.Close();
//Build POlygon Vertices
if (fence_type1 == "4")
{
query = "select polygon_latitude,polygon_longitude from tracking_master_fence_polygons where fence_id = '" + hid_fence_id.Value + "' and domain_id = '" + domain_id1 + "'";
dr1 = common.run_query(query, db1, cm1, dr1, 0);
if (dr1.HasRows)
{
while (dr1.Read())
{
vertices_x.Add(dr1["polygon_latitude"]);
vertices_y.Add(dr1["polygon_longitude"]);
}
}
dr1.Close();
points_polygon = vertices_x.Count;
}
//Create a Datatable of 14 rows
dt_fence.Columns.Add("fence_id", typeof(string));
dt_fence.Columns.Add("Date", typeof(string));
dt_fence.Columns.Add("Speed", typeof(string));
dt_fence.Columns.Add("Location", typeof(string));
dt_fence.Columns.Add("landmark_latitude", typeof(string));
dt_fence.Columns.Add("landmark_longitude", typeof(string));
dt_fence.Columns.Add("fence_latitude", typeof(string));
dt_fence.Columns.Add("fence_longitude", typeof(string));
dt_fence.Columns.Add("latitude", typeof(string));
dt_fence.Columns.Add("longitude", typeof(string));
dt_fence.Columns.Add("fence_size", typeof(string));
dt_fence.Columns.Add("fence_type", typeof(string));
dt_fence.Columns.Add("fence_status", typeof(string));
dt_fence.Columns.Add("object", typeof(string));
while (dr.Read())
{
fence_status = "";
float latitude = common.make_float(dr["latitude"].ToString());
float longitude = common.make_float(dr["longitude"].ToString());
if (fence_type1 == "1" || fence_type1 == "2")
{
if (((landmark_latitude1 * 100000) < (latitude * 100000) && (fence_latitude1 * 100000) > (latitude * 100000)) && ((landmark_longitude1 * 100000) < (longitude * 100000) && (fence_longitude1 * 100000) > (longitude * 100000)))
{
fence_status = "Inside";
}
else
{
fence_status = "Outside";
}
}
else if (fence_type1 == "3")
{
float ft = ((latitude * 100000) - (landmark_latitude1 * 100000));
float st = ((longitude * 100000) - (landmark_longitude1 * 100000));
float sqrt = common.make_float(Math.Sqrt((ft * ft) + (st * st)).ToString());
if (fence_size1 < sqrt)
{
fence_status = "Out Side";
}
else
{
fence_status = "In Side";
}
}
else if (fence_type1 == "4")
{
longitude_x = common.make_float(dr["latitude"].ToString());
latitude_y = common.make_float(dr["longitude"].ToString());
int i = 0, j = 0, c = 0;
for (i = 0, j = points_polygon - 1; i < points_polygon; j = i++)
{
float vertices_y_i_val = common.make_float(vertices_y[i].ToString());
float vertices_y_j_val = common.make_float(vertices_y[j].ToString());
float vertices_x_i_val = common.make_float(vertices_x[i].ToString());
float vertices_x_j_val = common.make_float(vertices_x[j].ToString());
if (((vertices_y_i_val > latitude_y != (vertices_y_j_val > latitude_y)) &&
(longitude_x < (vertices_x_j_val - vertices_x_i_val) * (latitude_y - vertices_y_i_val) / (vertices_y_j_val - vertices_y_i_val) + vertices_x_i_val)))
{
c = 1;
}
}
if (c == 1)
{
fence_status = "In Side";
}
else
{
fence_status = "Out Side";
}
}
dt_fence.Rows.Add(fence_id1, dr["added_date_time"], dr["speed"], dr["location"], landmark_latitude1, landmark_longitude1, fence_latitude1, fence_longitude1, latitude, longitude, fence_size1, fence_type1, fence_status, dr["object"]);
}//End of while Loop
//hid_ds_fence.Value = dt_fence.ToString();
gridview_fence.DataSource = dt_fence;
gridview_fence.DataBind();
}
dr.Close();
fence_modalpopup.Show();
}
In your code you're assigning EmptyDataText value after DataBind. It should be before DataBind. If "Message" is not going to change, you should rather define in HTML source as suggested.
You can use something like this
<Columns>
<Columns>
<EmptyDataTemplate>
<asp:Label ID="lblEmptydata" runat="server" Text="No Data here"></asp:Label>
</EmptyDataTemplate>
</asp:GridView>
Or can try this
in my remark gridview's row_databoundevent i wrote
if (e.Row.Cells[0].Text == " ") // to display text when there is no data
{
e.Row.Cells[0].Text = "No Data Found";
}
Or can try this too
dt.Rows.Add(dt.NewRow());
grid1.DataSource = dt;
grid1.DataBind();
int totalcolums = grid1.Rows[0].Cells.Count;
grid1.Rows[0].Cells.Clear();
grid1.Rows[0].Cells.Add(new TableCell());
grid1.Rows[0].Cells[0].ColumnSpan = totalcolums;
grid1.Rows[0].Cells[0].Text = "No Data Found";
Related
Getting old values in DataTable, I need new values which I updated. Please help me?
Update on button click
My code:
DataSet Ds = new DataSet();
string Query = "";
Query = "select Conv_0,Unit_0,Rate_0,Text_0,Barcode_0,Conv_1,Unit_1,Rate_1,Text_1,Barcode_1,Conv_2,Unit_2,Rate_2,Text_2,Barcode_2,Conv_3,Unit_3,Rate_3,Text_3,Barcode_3,Conv_4,Unit_4,Rate_4,Text_4,Barcode_4 from Prod_Unit where Code='" + a + "'";
Ds = SqlClass1.GetData_from_localhost(Query);
if (Ds.Tables[0].Rows.Count > 0)
{
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("NO");
dt.Columns.Add("UNITS");
dt.Columns.Add("CONVERSION");
dt.Columns.Add("BARCODE");
dt.Columns.Add("RATE 1");
dt.Columns.Add("RATE 2");
dt.Columns.Add("PRINT TEXT");
// dt.Rows.Add();
for (int i = 0; i < Ds.Tables[0].Columns.Count; i++)
{
if (i >= 0 && i <= 4)
{
dt.Rows.Add();
dt.Rows[i]["NO"] = i + 1;
string unit = Ds.Tables[0].Rows[0]["Unit_" + i + ""].ToString();
DataSet temp = SqlClass1.GetData_from_localhost("select Unit FROM Units where Code=" + unit + "");
if (temp.Tables[0].Rows.Count > 0)
{
dt.Rows[i]["UNITS"] = temp.Tables[0].Rows[0][0].ToString();
}
dt.Rows[i]["CONVERSION"] = Ds.Tables[0].Rows[0]["Conv_" + i + ""].ToString();
dt.Rows[i]["BARCODE"] = Ds.Tables[0].Rows[0]["Barcode_" + i + ""].ToString();
dt.Rows[i]["RATE 1"] = Ds.Tables[0].Rows[0]["Rate_" + i + ""].ToString();
dt.Rows[i]["RATE 2"] = Ds.Tables[0].Rows[0]["Rate_" + i + ""].ToString();
dt.Rows[i]["PRINT TEXT"] = Ds.Tables[0].Rows[0]["Text_" + i + ""].ToString();
}
}
if (i == 0)
{
// ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
// SetPreviousData();
}
}
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
SetPreviousData();// function to get previous data in
textbox
This is my binding function that I call in postback. How can I get updated values in ViewState["CurrentTable"] = dt;
on Update Button
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("NO");
dt.Columns.Add("UNITS");
dt.Columns.Add("CONVERSION");
dt.Columns.Add("BARCODE");
dt.Columns.Add("RATE 1");
dt.Columns.Add("RATE 2");
dt.Columns.Add("PRINT TEXT");
dr = dt.NewRow();
dr["NO"] = 1;
dr["UNITS"] = string.Empty;
dr["CONVERSION"] = string.Empty;
dr["BARCODE"] = string.Empty;
dr["RATE 1"] = string.Empty;
dr["RATE 2"] = string.Empty;
dr["PRINT TEXT"] = string.Empty;
dt.Rows.Add(dr);
int rowIndex = 0;
for (int i = 0; i < GridView1.Rows.Count; i ++)
{
if (GridView1.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
DropDownList box1 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox5");
TextBox box6 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox6");
dt.Rows[i]["NO"] = i + 1;
dt.Rows[i]["Units"] = box1.Text;
dt.Rows[i]["Conversion"] = box2.Text;
dt.Rows[i]["Barcode"] = box3.Text;
dt.Rows[i]["Rate 1"] = box4.Text;
dt.Rows[i]["Rate 2"] = box5.Text;
dt.Rows[i]["Print Text"] = box6.Text;
dt.Rows.Add();
rowIndex++;
}
}
ViewState["CurrentTable"] = dt;
Save();//function for save
}
I have an web application name travel. Every thing is working fine while working in test database even if i connect it to live database it works fine in local server but not working in live server.for ex.. I have a grid view to show the details where i can insert,delete,update and view but its working fine in my local server but in live server, my file are updating for the first time but if i try to update for the second time its not working. I have no idea whats happening can any one help me in this.
travel.cs
protected void gv_food_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_food.ShowFooter = true;
gv_food.EditIndex = -1;
Loadgv_food();
}
protected void gv_food_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AddConfirmDelete((GridView)sender, e);
hdnAmtvalue.Value = Convert.ToString((e.Row.RowIndex + 1) + (gv_food.PageSize * gv_food.PageIndex));
hdnAmtvalue.Value = Convert.ToString(Convert.ToInt16(hdnAmtvalue.Value) + 3);
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList drp = (DropDownList)e.Row.FindControl("drpfood");
sqlq = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sqlq += "\n UNION";
sqlq += "\n select DESCRIPTION,regionid from regionmaster";
ds = db.fillDataset(sqlq);
drp.DataSource = ds.Tables[0];
drp.DataTextField = "description";
drp.DataValueField = "regionid";
drp.DataBind();
DropDownList drpC = (DropDownList)e.Row.FindControl("drp_currency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = 2;
Load_CurrencyRate();
DropDownList ddlcurrency = (DropDownList)e.Row.FindControl("drp_currency");
int foodamt = Convert.ToInt32(hdnAmtvalue.Value);
TextBox ticketamount = (TextBox)e.Row.FindControl("txtamount");
TextBox inrate = (TextBox)e.Row.FindControl("txt_inrrate");
TextBox dollarrate = (TextBox)e.Row.FindControl("txt_dollarrate");
TextBox inramount = (TextBox)e.Row.FindControl("txt_inramount");
TextBox dollaramount = (TextBox)e.Row.FindControl("txt_dollaramount");
TextBox txtdate = (TextBox)e.Row.FindControl("txtfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ticketamount.Attributes.Add("ontextchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ddlcurrency.Attributes.Add("onchange", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculateticketfood(" + (e.Row.RowIndex + foodamt) + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
//inrate.Text = hdnAdvInrRate.Value.ToString();
inrate.Text = hdnAdvUsdRate.Value.ToString();
dollarrate.Text = hdnAdvUsdRate.Value.ToString();
//ddlcurrency.SelectedIndex = ddlcurrency.Items.IndexOf(ddlcurrency.Items.FindByText(hdnAdvCurrency.Value));
drp.SelectedIndex = drp.Items.IndexOf(drp.Items.FindByText(hdnRegion.Value));
}
}
protected void gv_food_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
sql = "delete from tmpintfoodexpenses where detailid=" + gv_food.DataKeys[e.RowIndex].Values[0].ToString() + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully deleted');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully deleted";
}
protected void gv_food_RowEditing(object sender, GridViewEditEventArgs e)
{
lblFoodException.Text = string.Empty;
try
{
gv_food.ShowFooter = false;
gv_food.EditIndex = e.NewEditIndex;
Loadgv_food();
//changes made on 25/jan/2012
DropDownList drp1 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEhr1");
DropDownList drp2 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEmin1");
DropDownList drp3 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEahr1");
DropDownList drp4 = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpEamin1");
sql = "select ARRIVALTIME,DEPATURETIME from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
//ds1 = db.fillDataset(sql);
DataTable dt = new DataTable();
dt = db.fillTable(sql);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["DEPATURETIME"].ToString().Contains(":"))
{
string[] _dhhmm = dt.Rows[0]["DEPATURETIME"].ToString().Trim().Split(new char[] { ':' });
if (_dhhmm[0].Trim() != null)
{
drp1.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[0].ToString()));
drp2.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_dhhmm[1].ToString()));
}
if (dt.Rows[0]["ARRIVALTIME"].ToString().Contains(":"))
{
string[] _ahhmm = dt.Rows[0]["ARRIVALTIME"].ToString().Trim().Split(new char[] { ':' });
if (_ahhmm[0].Trim() != null)
{
drp3.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[0].ToString()));
drp4.SelectedIndex = drp1.Items.IndexOf(drp1.Items.FindByText(_ahhmm[1].ToString()));
}
}
}
}
//End
sql = "select currencydescription,foodorperdiems from tmpintfoodexpenses where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds1 = db.fillDataset(sql);
currflag = ds1.Tables[0].Rows[0].ItemArray[0].ToString();
DropDownList drp = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drpefood");
sql = "SELECT ':Select:' AS DESCRIPTION,0 AS regionid FROM dual";
sql += "\n UNION";
sql += "\n select description,regionid from regionmaster";
setDataSource(drp, sql);
DropDownList ddlFood = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("ddlFoodOrPerdiems");
ddlFood.SelectedValue = ds1.Tables[0].Rows[0].ItemArray[1].ToString();
Label lblregion = (Label)gv_food.Rows[e.NewEditIndex].FindControl("lblf");
lblregion.Visible = false;
drp.SelectedIndex = (drp.Items.IndexOf(drp.Items.FindByText(lblregion.Text.ToString())));
DropDownList drpC = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
sqlq = "SELECT 0 AS CURRENCYID,':Select:' AS DESCRIPTION FROM dual";
sqlq += "\n UNION";
sqlq += "\n select CURRENCYID,DESCRIPTION from currencymaster";
ds1 = db.fillDataset(sqlq);
drpC.DataSource = ds1.Tables[0];
drpC.DataTextField = "description";
drpC.DataValueField = "currencyid";
drpC.DataBind();
drpC.SelectedIndex = drpC.Items.IndexOf(drpC.Items.FindByText(currflag));
indexrow = gv_food.Rows[e.NewEditIndex].RowIndex.ToString();
rowindex = int.Parse(indexrow);
rowindex = rowindex + 2;
DropDownList ddlcurrency = (DropDownList)gv_food.Rows[e.NewEditIndex].FindControl("drp_ecurrency");
TextBox ticketamount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUamount");
TextBox inrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einrrate");
TextBox dollarrate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollarrate");
TextBox inramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_einramount");
TextBox dollaramount = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txt_edollaramount");
TextBox txtdate = (TextBox)gv_food.Rows[e.NewEditIndex].FindControl("txtUfromdate");
ticketamount.Attributes.Add("onkeypress", "return chkNumber()");
dollarrate.Attributes.Add("onkeypress", "return chkNumber()");
inrate.Attributes.Add("onkeypress", "return chkNumber()");
ddlcurrency.Attributes.Add("onchange", "Calculatefoodedit(" + rowindex + ")");
ticketamount.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
dollarrate.Attributes.Add("Onkeyup", "Calculatefoodedit(" + rowindex + ")");
inramount.Attributes.Add("readonly", "readonly");
dollaramount.Attributes.Add("readonly", "readonly");
txtdate.Attributes.Add("readonly", "readonly");
}
catch (Exception ex)
{
}
}
protected void gv_food_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
indexrow = "";
rowindex = 0;
GridViewRow row1 = gv_food.Rows[e.RowIndex];
TextBox tfromdate = row1.FindControl("txtUfromdate") as TextBox;
TextBox ttodate = row1.FindControl("txtUtodate") as TextBox;
DropDownList ddlfood = (DropDownList)row1.FindControl("ddlFoodOrPerdiems");
DropDownList ddl = (DropDownList)row1.FindControl("drpefood");
TextBox txtdescription = row1.FindControl("txtUdescription") as TextBox;
TextBox txtreference = row1.FindControl("txtUreference") as TextBox;
TextBox tAmt = row1.FindControl("txtUAmount") as TextBox;
//DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
Label tid = row1.FindControl("lblEid") as Label;
DropDownList drpccy = (DropDownList)row1.FindControl("drpEccy") as DropDownList;
DropDownList eddl_curr = (DropDownList)row1.FindControl("drp_ecurrency");
TextBox edcurrentrate = (TextBox)row1.FindControl("txt_edollarrate");
TextBox edamount = (TextBox)row1.FindControl("txt_edollaramount");
TextBox eicurrentrate = (TextBox)row1.FindControl("txt_einrrate");
TextBox eiamount = (TextBox)row1.FindControl("txt_einramount");
//changes made on 25/jan/2012
TextBox txtENoOfDays = row1.FindControl("txtENoOfDays") as TextBox;
DropDownList drpEhr1 = row1.FindControl("drpEhr1") as DropDownList;
DropDownList drpEmin1 = row1.FindControl("drpEmin1") as DropDownList;
DropDownList drpEahr1 = row1.FindControl("drpEahr1") as DropDownList;
DropDownList drpEamin1 = row1.FindControl("drpEamin1") as DropDownList;
//End
if (tfromdate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the From Date');</script>");
lblFoodException.Text = "* Enter the From Date";
tfromdate.Focus();
return;
}
//changes made on 25/jan/2012
if (drpEhr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Hours.";
drpEhr1.Focus();
return;
}
if (drpEmin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Depature Minute.";
drpEmin1.Focus();
return;
}
//End
if (ttodate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the To Date');</script>");
lblFoodException.Text = "* Enter the To Date";
ttodate.Focus();
return;
}
if (drpEahr1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Hours.";
drpEahr1.Focus();
return;
}
if (drpEamin1.SelectedIndex <= 0)
{
lblFoodException.Text = "* Select the Arrival Minue.";
drpEahr1.Focus();
return;
}
//End
if (ddlfood.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the Food or Perdiems');</script>");
lblFoodException.Text = "* Select the Food or Perdiems";
ddl.Focus();
return;
}
if (ddl.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Select the region');</script>");
lblFoodException.Text = "* Select the region";
ddl.Focus();
return;
}
if (txtdescription.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Description');</script>");
lblFoodException.Text = "* Enter the Description";
txtdescription.Focus();
return;
}
if (txtreference.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Reference');</script>");
lblFoodException.Text = "* Enter the Reference";
txtreference.Focus();
return;
}
if (eddl_curr.SelectedIndex <= 0)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the Currencyid');</script>");
lblFoodException.Text = "* Successfully Updated";
eddl_curr.Focus();
return;
}
if (edcurrentrate.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edcurrentrate.Focus();
return;
}
if (edamount.Text.Trim() == string.Empty)
{
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
edamount.Focus();
return;
}
if (eicurrentrate.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eicurrentrate.Focus();
return;
}
if (eiamount.Text.Trim() == string.Empty)
{
// ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Enter the amount');</script>");
lblFoodException.Text = "* Successfully Updated";
eiamount.Focus();
return;
}
//changes made on 25/jan/2012
if (Convert.ToInt32(drpEhr1.SelectedItem.Text) >= 12)
{
Ehh = "PM";
}
else
{
Ehh = "AM";
}
if (Convert.ToInt32(drpEahr1.SelectedItem.Text) >= 12)
{
Emm = "PM";
}
else
{
Emm = "AM";
}
DateTime t1 = Convert.ToDateTime(tfromdate.Text.ToString() + " " + drpEhr1.SelectedItem.Text.ToLower() + ":" + drpEmin1.SelectedItem.Text.ToString() + " " + Ehh);
DateTime t2 = Convert.ToDateTime(ttodate.Text.ToString() + " " + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + " " + Emm);
tp1 = t2.Subtract(t1);
string[] EgetInfo = Convert.ToString(tp1).Split(new char[] { '.' });
if (EgetInfo.Length > 1) // Day calculating
{
Enodays = EgetInfo[0];
string[] EgetHours = EgetInfo[1].ToString().Split(new char[] { ':' });
if (Convert.ToInt32(EgetHours[0].ToString()) >= 6 && Convert.ToInt32(EgetHours[0].ToString()) < 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 0.50;
}
else if (Convert.ToInt32(EgetHours[0].ToString()) >= 12)
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString()) + 1;
}
else
{
EtotalDays = Convert.ToDouble(EgetInfo[0].ToString());
}
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " PM";
EtotTime = Ehh.ToString() + ":" + Emm.ToString() + " AM";
}
else//Hours Calculating
{
string[] EgetHours = EgetInfo[0].ToString().Split(new char[] { ':' });
Enodays = "0";
hh = EgetHours[0];
mm = EgetHours[1];
if (Convert.ToInt32(hh.ToString()) >= 6 && Convert.ToInt32(hh.ToString()) < 12)
{
EtotalDays = 0.50;
}
else if (Convert.ToInt32(hh.ToString()) >= 12)
{
EtotalDays = 1;
}
if (Convert.ToInt32(hh.ToString().Length) > 12)
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " PM";
}
else
{
EtotTime = hh.ToString() + ":" + mm.ToString() + " AM";
}
}
txtENoOfDays.Text = Convert.ToString(EtotalDays);
//End
sqlq = "select min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds3 = db.fillDataset(sqlq);
if (ds3.Tables[0].Rows.Count > 0)
{
fromdate = ds3.Tables[0].Rows[0].ItemArray[0].ToString();
todate = ds3.Tables[0].Rows[0].ItemArray[1].ToString();
}
string from = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
string to = Convert.ToDateTime(ttodate.Text).ToString("dd/MMM/yyyy");
//string date = Convert.ToDateTime(tfromdate.Text).ToString("dd/MMM/yyyy");
bool x = ((Convert.ToDateTime(from) >= Convert.ToDateTime(fromdate)) && (Convert.ToDateTime(to) <= Convert.ToDateTime(todate)));
if (x == false)
{
//ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('Date should be between departure date and arrival date '); </script>");
lblFoodException.Text = "* Date should be between departure date and arrival date";
tfromdate.Text = "";
return;
}
bool y = (Convert.ToDateTime(from) <= Convert.ToDateTime(todate));
if (y == false)
{
// ClientScript.RegisterStartupScript(this.GetType(), "ma", "<script> alert('invalid date '); </script>");
tfromdate.Text = "";
lblFoodException.Text = "Invalid Date";
return;
}
int curr8 = 1;
//Poovaragavan P changes made on 25/jan/2012
sqlq = "select min(DEPATURETIME),max(ARRIVALTIME),min(traveldate),max(dateofreturn) from tmpinttravelclaimsdetail where headid='" + Label22.Text + "'and EmpId=" + Session["UserId"].ToString() + " and EmpType='" + Session["EmployeeType"].ToString() + "'";
ds5 = db.fillDataset(sqlq);
if (ds5.Tables[0].Rows.Count > 0)
{
EDepTime = ds5.Tables[0].Rows[0].ItemArray[0].ToString();
EArrTime = ds5.Tables[0].Rows[0].ItemArray[1].ToString();
EDepDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[2].ToString()).ToString("dd/MM/yyy");
EArrDate = Convert.ToDateTime(ds5.Tables[0].Rows[0].ItemArray[3].ToString()).ToString("dd/MM/yyyy");
}
if (EDepDate == Convert.ToDateTime(from.ToString()).ToString("dd/MM/yyyy") && EArrDate.ToString() == Convert.ToDateTime(to.ToString()).ToString("dd/MM/yyy"))
{
if ((EDepTime != drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString()) || (EArrTime != drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString()))
{
lblFoodException.Text = "Time should be Equal to departure Time and arrival Time";
lblFoodException.ForeColor = System.Drawing.Color.Red;
drpEhr1.SelectedIndex = 0;
drpEmin1.SelectedIndex = 0;
drpEahr1.SelectedIndex = 0;
drpEamin1.SelectedIndex = 0;
drpEhr1.Focus();
return;
}
}
//End
sql = " Update tmpintfoodexpenses set Expensedate=to_Date('" + tfromdate.Text + "','dd/mon/yyyy'),";
sql += " Expensetodate=to_Date('" + ttodate.Text + "','dd/mon/yyyy'),";
sql += " FOODORPERDIEMS='" + ddlfood.SelectedItem.Value.ToString() + "',";
sql += " region=" + ddl.SelectedItem.Value.ToString() + ",";
sql += " DESCRIPTION='" + mod.checkforapostrophe(txtdescription.Text) + "',";
sql += " REFERENCE='" + mod.checkforapostrophe(txtreference.Text) + "',";
sql += " amount=" + mod.checkforapostrophe(tAmt.Text) + ",";
sql += " Currencyid=" + eddl_curr.SelectedItem.Value + ",";
sql += " currencydescription='" + mod.checkforapostrophe(eddl_curr.SelectedItem.Text) + "',";
sql += " dollarcurrentrate=" + mod.checkforapostrophe(edcurrentrate.Text) + ",";
sql += " dollaramount=" + mod.checkforapostrophe(edamount.Text) + ",";
sql += " inrcurrentrate=" + mod.checkforapostrophe(eicurrentrate.Text) + ",";
sql += " inramount=" + mod.checkforapostrophe(eiamount.Text) + ",";
//Poovaragavan P changes made on 25/jan/2012
sql += " NOOFDAYS='" + mod.checkforapostrophe(txtENoOfDays.Text) + "',";
sql += " ARRIVALTIME='" + drpEahr1.SelectedItem.Text.ToString() + ":" + drpEamin1.SelectedItem.Text.ToString() + "',";
sql += " DEPATURETIME='" + drpEhr1.SelectedItem.Text.ToString() + ":" + drpEmin1.SelectedItem.Text.ToString() + "',";
sql += " TOTALTIME='" + EtotTime.ToString() + "'";
//End
sql += " where detailid =" + mod.checkforapostrophe(tid.Text) + "";
db.Executecommand(sql);
gv_food.EditIndex = -1;
gv_food.ShowFooter = true;
Loadgv_halting();
Loadgv_ticket();
Loadgv_local();
Loadgv_other();
Loadgv_food();
//ClientScript.RegisterStartupScript(this.GetType(), "add", "<script>alert('Successfully Updated');</script>");
lblFoodException.ForeColor = System.Drawing.Color.Green;
lblFoodException.Text = "* Successfully Updated";
}
I am new to JAVA. I am trying to export Excel through servlet from resultset.
When i am trying to store data in String buffer the it is not actually saving it.
Testfirst.java
String assingee_name = req.getParameter("firstName");
String track_name = req.getParameter("track");
String sla_id = req.getParameter("sla");
StringBuffer sb = new StringBuffer();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Databasethree");
stmt = con.createStatement();
//pw.println("'" +assingee_name + "'");
length = track_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where track =" + "'" + track_name + "'");
}
length = sla_id.length();
if (length > 0) {
//rs = stmt.executeQuery("SELECT* FROM casedetails where case_age >"+"'" +sla_id + "'");
rs = stmt.executeQuery("SELECT* FROM cdoscase where Incident_Submit_Fiscal_Year=" + "'" + sla_id + "'");
}
length = assingee_name.length();
if (length > 0) {
rs = stmt.executeQuery("SELECT* FROM casedetails where Assingee_name =" + "'" + assingee_name + "'");
}
pw.println("<html><body>");
pw.println("<H1> CDOS Case Management Version 1.1 </H1>");
pw.println("<Head><style>table,th,td{border:1px solid black;}</style></head>");
pw.println("<table>");
ResultSetMetaData rm = rs.getMetaData();
int clm = rm.getColumnCount();
StringBuffer sb1 = new StringBuffer();
String sb2 = new String();
for (int j = 1; j <= clm; j++) {
sb2 = rm.getColumnName(j);
pw.println("<th>");
pw.println(sb2);
pw.println("</th>");
}
ArrayList Rows = new ArrayList();
ArrayList row = new ArrayList();
Object a = new Object();
int jj = 0; // to find out the number rows
while (rs.next()) {
jj = jj + 1;
pw.println("<tr>");
for (int i = 1; i <= clm; i++) {
//data1[i]=rs.getString(i);
pw.println("<td>");
//pw.println(rs.getObject(i).toString());
pw.println(rs.getString(i));
pw.println("</td>");
sb2.append(rs.getString(i);
//row.add(rs.getString(i));
//sb2=sb2+rs.getObject(i).toString();
}
pw.println("</tr>");
} sb1.append("fd");
//Rows.add(row);
pw.println("Total Records found" + sb1);
pw.println("</table>");
//sb2=sb2+rs.getObject(clm).toString();
//sb1.append(sb2);
//sb1.append(sb2);
a = rs.getString(4).toString();
pw.println("this is data " + a);
pw.println("<p>");
pw.println("<td>Do you want to download report </td>");
req.setAttribute("data", Rows);
pw.println("<input type=\"submit\" name =\"submit1\" value=\"Export To Excel\">");
pw.println("</form>");
} catch (SQLException e) {
pw.println(e.getNextException());
} catch (ClassNotFoundException e) {
pw.println(e.getException());
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
pw.close();
}
}
}
Any help on this is highly appreciated.
Thanks,
SR
I have two repeater controls one inside other and in inner repeater there is placeholder in which radio button is dynamically generated. I want to find the radio button control to check whether it is checked or not? I want above all function to be performed in button submit/click event defined in the code?
if (!Page.IsPostBack)
{
//1) Load SomeDatatable from Database somehow
// Just for testing : replace with query to DB
strqry = "select * from Quiz_tblQsnsLimitMaster where Qsnexamname='" + Request.QueryString["QsnEname"].ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(strqry, sCon);
DataSet ds = new DataSet();
try
{
adp.Fill(ds);
int total = ds.Tables[0].Rows.Count;
for (int i = 0; i < total; i++)
{
string QuesID = ds.Tables[0].Rows[i].ItemArray[1].ToString();
//SubName = ds.Tables[0].Rows[i].ItemArray[3].ToString();
DataSet oDs = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_OnlineTest_QuestionsWithOptions_Get", QuesID);
SomeDatatable.Merge(oDs.Tables[0]);
}
removeDuplicatesRows(SomeDatatable);
System.Data.DataColumn newColumn = new System.Data.DataColumn("ContentIndex", typeof(System.String));
newColumn.DefaultValue = "0";
SomeDatatable.Columns.Add(newColumn);
for (int i = 0; i < Math.Ceiling((decimal)SomeDatatable.Rows.Count); i++)
SomeDatatable.Rows[i]["ContentIndex"] = i + 1;
}
catch
{
}
////2) Create a dummy data source for the tab repeater using a list of anonymous types
List<object> TabList = new List<object>();
//BindSubject();
for (int I = 0; I < Math.Ceiling((decimal)SomeDatatable.Rows.Count / (decimal)ContentPerTab); I++)
{
TabList.Add(new { TabIndex = I });
}
TabRepeater.ItemDataBound += TabRepeater_ItemDataBound;
TabRepeater.DataSource = TabList;
TabRepeater.DataBind();
//TablLinkRepeater.DataSource = TabList;
//TablLinkRepeater.DataBind();
//}
}
public void removeDuplicatesRows(DataTable dt)
{
SomeDatatable = dt.DefaultView.ToTable(true, "QuestionId");
}
protected void TabRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
int TabIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "TabIndex").ToString(), out TabIndex);
//Copy Content Rows from SomeDatable that belong to this tab
DataTable Dt = SomeDatatable.Clone();
for (Int32 i = TabIndex * ContentPerTab; i <= (TabIndex + 1) * ContentPerTab - 1; i++)
{
if (i >= SomeDatatable.Rows.Count) break;
Dt.ImportRow(SomeDatatable.Rows[i]);
}
// Find the content repeater in this item and use the new datatable as source
Repeater ContentRepeater = (Repeater)e.Item.FindControl("ContentRepeater");
ContentRepeater.ItemDataBound += ContentRepeater_ItemDataBound;
ContentRepeater.DataSource = Dt;
ContentRepeater.DataBind();
}
}
// This handler might be needed for content repeater, included just for testing
protected void ContentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
//Read coulmn from Datarow
int ContentIndex = -1;
int.TryParse(DataBinder.Eval(e.Item.DataItem, "ContentIndex").ToString(), out ContentIndex);
var parsed = "'" + HttpUtility.ParseQueryString(DataBinder.Eval(e.Item.DataItem, "QuestionID").ToString()) + "'";
//Add Question
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", Convert.ToString(parsed));
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
int iCnt = 0;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Table tblQsn = new Table();
//.....Begin Text Qsn Creation.....//
tblQsn.Width = new Unit("98%");
TableRow trQsn = new TableRow();
iRowCounter++;
trQsn.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsn = new TableCell();
TableCell tcQsnSNo = new TableCell();
tcQsn.CssClass = "Label";
tcQsn.BackColor = System.Drawing.Color.Gainsboro;
tcQsn.Font.Bold = true;
tcQsn.Font.Size = 12;
tcQsn.Text = ds.Tables[0].Rows[i][1].ToString();
tcQsn.Width = Unit.Percentage(99.5);
iCellCounter++;
tcQsn.ID = "Cell_" + iCellCounter.ToString();
tcQsnSNo.CssClass = "Label";
tcQsnSNo.Attributes.Add("valign", "top");
tcQsnSNo.BackColor = System.Drawing.Color.Gainsboro;
tcQsnSNo.Font.Bold = true;
tcQsnSNo.Width = Unit.Percentage(0.5);
iCellCounter++;
tcQsnSNo.ID = "Cell_" + iCellCounter.ToString();
iCnt++;
tcQsnSNo.Text = ContentIndex.ToString() + ".";
trQsn.Cells.Add(tcQsnSNo);
trQsn.Cells.Add(tcQsn);
tblQsn.Rows.Add(trQsn);
int rcnt = i;
int iOptCnt = 0;
string sStatus = "N";
while ((rcnt >= 0) && (rcnt < ds.Tables[0].Rows.Count))
{
if (ds.Tables[0].Rows[rcnt][2].ToString() == ds.Tables[0].Rows[i][2].ToString())
{
if (sStatus == "N")
{
sStatus = "Y";
}
TableRow trQsnOpt = new TableRow();
iRowCounter++;
trQsnOpt.ID = "Row_" + iRowCounter.ToString();
TableCell tcQsnOpt = new TableCell();
tcQsnOpt.CssClass = "Label";
iCellCounter++;
tcQsnOpt.ID = "Cell_" + iCellCounter.ToString();
tcQsnOpt.Attributes.Add("valign", "top");
tcQsnOpt.VerticalAlign = VerticalAlign.Middle;
TableCell tcQsnOptSNo = new TableCell();
tcQsnOptSNo.CssClass = "Label";
iCellCounter++;
tcQsnOptSNo.ID = "Cell_" + iCellCounter.ToString();
iOptCnt++;
RadioButton oRbOptions = new RadioButton();
oRbOptions.GroupName = ds.Tables[0].Rows[rcnt][2].ToString() + "_Group";
oRbOptions.Text = ds.Tables[0].Rows[rcnt][3].ToString().Trim();
oRbOptions.Font.Size = 11;
iRbTCounter++;
oRbOptions.ID = ds.Tables[0].Rows[i][0].ToString() + "_" + ds.Tables[0].Rows[rcnt][2].ToString() + "_" + "Option" + iOptCnt.ToString() + "_" + iRbTCounter.ToString();
//oRbOptions.Enabled = false;
//if (ds.Tables[0].Rows[i][2].ToString() == "Option" + iRbTCounter.ToString())
//{
// oRbOptions.Checked = true;
//}
oRbOptions.InputAttributes.Add("data-info", Convert.ToString(ContentIndex));
oRbOptions.CssClass = "Label";
tcQsnOpt.Controls.Add(oRbOptions);
tcQsnOptSNo.Text = iOptCnt.ToString() + ".";
trQsnOpt.Cells.Add(tcQsnOptSNo);
trQsnOpt.Cells.Add(tcQsnOpt);
rcnt++;
//.....Add Option Image.....//
tblQsn.Rows.Add(trQsnOpt);
}
else
break;
}
i = rcnt - 1;
PlPreview = (PlaceHolder)e.Item.FindControl("PlPreview");
PlPreview.Controls.Add(tblQsn);
}
}
}
}
}
protected void btnsubmit_Click(object sender, EventArgs e)
{
SubmitQuestion();
}
public void SubmitQuestion()
{
for (int c = 0; c < SomeDatatable.Rows.Count; c++)
{
string sQsnOptId = SomeDatatable.Rows[c]["QuestionID"].ToString();
DataSet ds = SqlHelper.ExecuteDataset(sCon, "Ps_Quiz_QuestionsWithOptions_Get", "'" + sQsnOptId + "'");
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i-1][2].ToString() + "_" + "Option" + i + "_" + i;
Repeater rpt = (Repeater)TabRepeater.NamingContainer.FindControl("ContentRepeater");
RadioButton rbt = (RadioButton)rpt.NamingContainer.FindControl(rdboption);
if (rbt.Checked)
{
strqry = "update Quiz_tblOnlineTest_Detail set UserAns='Option" + i + "', DeletionStatus='A' where CreationLogInId='AMITSAMBYAL#HOTMAIL.COM' and ExamName='" + Request.QueryString["QsnEname"].ToString() + "' and QsnId=" + Session["quesid"].ToString() + "";
cmd = new SqlCommand(strqry, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
}
finally
{
con.Close();
}
break;
}
}
}
}
}
I found the answer. Thanks
foreach (RepeaterItem repeater in TabRepeater.Items)
{
Repeater repeater1 = (Repeater)repeater.FindControl("ContentRepeater");
foreach (RepeaterItem repItem in repeater1.Items)
{
for (int i = 1; i <= 4; i++)
{
string rdboption = ds.Tables[0].Rows[c][0].ToString() + "_" + ds.Tables[0].Rows[i - 1][2].ToString() + "_" + "Option" + i + "_" + i;
PlaceHolder PlPreview = (PlaceHolder)repItem.FindControl("PlPreview");
rbt = (RadioButton)PlPreview.FindControl(rdboption);
if (rbt.Checked)
{
// statement
}
}
}
}
}
}
I want to make shopping cart Datatable, I wrote the following code here to make the list of products
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
dt.Constraints.Add("Proid_PK", dt.Columns[0], true);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
return dt;
}
It binds the data fine with no problem, but where I insert the same row with same value it inserted in new record in the gridview, I don't want it like that I want update just one cell (I mean when I add new record with same values I want Quantity value on increase without adding new record in gridview) like I mark on the image
after long testing and googleing i finally get it done , here the code i used
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataView dv = dt.DefaultView;
dv.Sort = "ProName";
int found;
string Proname;
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
Proname = dr[0].ToString();
found = dv.Find(Proname);
if (found != -1)
{
foreach (DataRow pro in dt.Rows)
{
for (int x = 0; x < dt.Rows.Count; x++)
{
if (dt.Rows[x]["ProName"].ToString()==Proname)
{
dt.Rows[x]["quantity"] = Convert.ToInt16(dt.Rows[x]["quantity"]) + quantity;
}
}
}
}
}
}
return dt;
}
You could use LINQ:
DataTable dt = new DataTable("products");
dt.Columns.Add("ProName", typeof(string));
dt.Columns.Add("odate", typeof(DateTime));
dt.Columns.Add("ocountry", typeof(string));
dt.Columns.Add("oarea", typeof(string));
dt.Columns.Add("oaddress", typeof(string));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("price", typeof(decimal));
dt.Columns.Add("SubTotal", typeof(decimal));
DataRow dr1 = dt.NewRow();
dr1[0] = "test";
dr1[1] = new DateTime(2005, 5, 15);
dr1[2] = "US";
dr1[3] = "test area";
dr1[4] = "555";
dr1[5] = 1;
dr1[6] = 5.25;
dr1[7] = 5.25 * 1;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "test";
dr2[1] = new DateTime(2005, 5, 15);
dr2[2] = "US";
dr2[3] = "test area";
dr2[4] = "555";
dr2[5] = 3;
dr2[6] = 5.25;
dr2[7] = 5.25 * 3;
dt.Rows.Add(dr2);
var shoppingCart = from r in dt.AsEnumerable()
group r by new
{
ProName = r.Field<string>("ProName"),
odate = r.Field<DateTime>("odate"),
ocountry = r.Field<string>("ocountry"),
oarea = r.Field<string>("oarea"),
oaddress = r.Field<string>("oaddress"),
price = r.Field<decimal>("price")
} into g
select new
{
g.Key.ProName,
g.Key.odate,
g.Key.ocountry,
g.Key.oarea,
g.Key.oaddress,
g.Key.price,
quantity = g.Sum(s1 => s1.Field<int>("quantity")),
SubTotal = g.Sum(s2 => s2.Field<decimal>("SubTotal"))
};
foreach (var p in shoppingCart)
{
Console.WriteLine("Product: {0}, Quantity: {1}, Subtotal: {2}", p.ProName, p.quantity, p.SubTotal);
}
Results:
Product: test, Quantity: 4, Subtotal: 21.00