Unable to update the textbox values in the gridview[c# asp.net] - asp.net

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
}

Related

Sorting table when used with literalControl ASP.net

I have a problem sorting this table. This was just a project that was pass unto me, and they want me to make some changes with the codes. Here's the code used to create table with data.
DataTable dt = common.get_entry(sname);
if (dt.Rows.Count != 0)
{
error_msg.Visible = false;
loader4.Visible = true;
}
else
{
loader4.Visible = false;
error_msg.Visible = true;
}
int maxsize = 10;
int rpage = Convert.ToInt32(p);
int startrow = ((rpage - 1) * maxsize) + 1;
int endrow = (rpage * maxsize);
if (dt.Rows.Count > 0)
{
int rcnt = dt.Rows.Count;
var tbl = view_tbl;
view_tbl.CssClass = "table table-hover table-bordered";
var maxpage = rcnt / maxsize;
var excess = rcnt % maxsize;
if (excess > 0) maxpage++;
TableHeaderRow r1 = new TableHeaderRow();
r1.TableSection = TableRowSection.TableHeader;
TableHeaderCell c2 = new TableHeaderCell();
c2.Controls.Add(new LiteralControl(""));
c2.Width = 45;
r1.Cells.Add(c2);
TableHeaderCell c8 = new TableHeaderCell();
c8.Controls.Add(new LiteralControl("Store Code"));
c8.Width = 120;
r1.Cells.Add(c8);
TableHeaderCell c3 = new TableHeaderCell();
c3.Controls.Add(new LiteralControl("Store Name"));
c3.Width = 250;
r1.Cells.Add(c3);
TableHeaderCell c4 = new TableHeaderCell();
c4.Controls.Add(new LiteralControl("Line of Business"));
c4.Width = 150;
r1.Cells.Add(c4);
TableHeaderCell c5 = new TableHeaderCell();
c5.Controls.Add(new LiteralControl("Visitors Name"));
c5.Width = 170;
r1.Cells.Add(c5);
TableHeaderCell c7 = new TableHeaderCell();
c7.Controls.Add(new LiteralControl("Date of Visit"));
c7.Width = 100;
r1.Cells.Add(c7);
TableHeaderCell c9 = new TableHeaderCell();
c9.Controls.Add(new LiteralControl("Added Date"));
c9.Width = 170;
r1.Cells.Add(c9);
TableHeaderCell c6 = new TableHeaderCell();
c6.Controls.Add(new LiteralControl("Action"));
c6.Width = 100;
r1.Cells.Add(c6);
tbl.Rows.Add(r1);
for (int cnt = startrow - 1; cnt < rcnt && cnt < endrow; cnt++)
{
TableRow r = new TableRow();
String sn = dt.Rows[cnt][3].ToString();
String lo = dt.Rows[cnt][5].ToString();
String id = dt.Rows[cnt][0].ToString();
String vn = dt.Rows[cnt][4].ToString();
String ed = dt.Rows[cnt][1].ToString();
String da = dt.Rows[cnt][6].ToString();
String sc = dt.Rows[cnt][7].ToString();
string[] edd = new string[2];
edd = ed.Split(' ');
ed = edd[0] + " " + dt.Rows[cnt][2].ToString();
TableCell cc1 = new TableCell();
cc1.Controls.Add(new LiteralControl("<input class='check_box' rel='" + id + "'type='checkbox'> <a href='#'><i class='icon-star-empty'></i></a>"));
r.Cells.Add(cc1);
TableCell cc2 = new TableCell();
cc2.Controls.Add(new LiteralControl("<strong>" + sc + "</strong>"));
r.Cells.Add(cc2);
TableCell cc7 = new TableCell();
cc7.Controls.Add(new LiteralControl("<strong>" + sn + "</strong>"));
r.Cells.Add(cc7);
TableCell cc3 = new TableCell();
cc3.Controls.Add(new LiteralControl("<strong>" + lo + "</strong>"));
r.Cells.Add(cc3);
TableCell cc4 = new TableCell();
cc4.Controls.Add(new LiteralControl("<strong>" + vn + "</strong>"));
r.Cells.Add(cc4);
TableCell cc5 = new TableCell();
cc5.Controls.Add(new LiteralControl("<strong>" + ed + "</strong>"));
r.Cells.Add(cc5);
TableCell cc8 = new TableCell();
cc8.Controls.Add(new LiteralControl("<strong>" + da + "</strong>"));
r.Cells.Add(cc8);
TableCell cc6 = new TableCell();
cc6.Controls.Add(new LiteralControl("<a data-target='#viewentry' data-toggle='modal' class='btn btn-mini btn-success view_btn' rel='" + id + "'><i class='icon-th-list icon-white'></i> View</a> <a data-target='#delentry' data-toggle='modal' class='btn btn-mini btn-danger del_btn hidden' rel='" + id + "'><i class='icon-trash icon-white'></i></a>"));
r.Cells.Add(cc6);
tbl.Rows.Add(r);
}
var dpagi = pagi;
LiteralControl ul = new LiteralControl();
ul.Text = "<ul>";
for (int cnt5 = 1; cnt5 <= maxpage; cnt5++)
{
if (cnt5 == rpage)
ul.Text = ul.Text + "<li class='disabled'><a href='StoreVisitView.aspx?page=" + cnt5 + "'>" + cnt5 + "</a></li>";
else
ul.Text = ul.Text + "<li><a href='StoreVisitView.aspx?page=" + cnt5 + "' class='pgn'>" + cnt5 + "</a></li>";
}
ul.Text = ul.Text + "</ul>";
dpagi.Controls.Add(ul);
pagi.CssClass = "pagination";
loader4.Visible = false;
I have no idea how to sort this because the table was made thru literalcontrol and etc..
If you want to sort the data on server side I suggest using a DataView to sort it. After it's sorted you can render it manually as you do now (iterate through DataView's rows) or bind a DataGrid to it.
DataView view = new DataView(dt);
view.Sort = "Column ASC, Column2 ASC";
// Now iterate through rows of dataview
foreach (DataRowView row in view) {...}
Other option is to sort it on client side using some sorting plugin.
For example Tablesorter seems pretty easy to use. Or just google "sort table javascript"...

how to add button in Dynamic gridview?

public void BuildMeatTally()
{
try
{
DataTable dtdate = new DataTable();
objRetailPL.status = 4;
dtdate = objRetailBAL.GetTypeNew(objRetailPL);
if (dtdate.Rows.Count > 0)
{
for (int i = 0; i < dtdate.Rows.Count; i++)
{
string branchdate;
int totbirds; float totwt, meatyield, Avgweight;
DateTime datewr;
DataTable dtdatedetailsTable = new DataTable();
objRetailPL.branchdate = dtdate.Rows[i]["BranchDate"].ToString();
objRetailPL.sno = Convert.ToInt32(dtdate.Rows[i]["sno"].ToString());
dtdatedetailsTable = objRetailBAL.getbradisdatewisedet(objRetailPL);
branchdate = dtdatedetailsTable.Rows[0]["BranchDate"].ToString();
totbirds = Convert.ToInt32(dtdatedetailsTable.Rows[0]["numofbirds"].ToString());
totwt = Convert.ToSingle(dtdatedetailsTable.Rows[0]["totalweght"].ToString());
meatyield = Convert.ToSingle(dtdatedetailsTable.Rows[0]["totalmeatyeild"].ToString());
Avgweight = Convert.ToSingle(dtdatedetailsTable.Rows[0]["AvgWeight"].ToString());
Table tbldynamic = new Table();
tbldynamic.BorderStyle = BorderStyle.Ridge;
tbldynamic.Width = 600;
TableCell tc = new TableCell();
TableRow tr = new TableRow();
Label lblbranchdate = new Label();
lblbranchdate.ID = "lblbrandate" + i.ToString();
lblbranchdate.Text = "&nbsp&nbsp" + "<B>Branch Date:</B>" + "&nbsp";
tc.Controls.Add(lblbranchdate);
Label lblbranchdatedata = new Label();
lblbranchdatedata.ID = "lbltotnumbird1" + i.ToString();
lblbranchdatedata.Text = branchdate + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lblbranchdatedata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
Label lbltotwt1 = new Label();
lbltotwt1.ID = "lbltotwt1" + i.ToString();
lbltotwt1.Text = "<B>Total Weight:</B>" + "&nbsp";
tc.Controls.Add(lbltotwt1);
Label lbltotwt1data = new Label();
lbltotwt1data.ID = "lbltotwt1data" + i.ToString();
lbltotwt1data.Text = totwt + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lbltotwt1data);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
tc = new TableCell();
tr = new TableRow();
Label lbltotbirds = new Label();
lbltotbirds.ID = "lbltotbird" + i.ToString();
lbltotbirds.Text = "<B>Total Birds:</B>" + "&nbsp";
tc.Controls.Add(lbltotbirds);
Label lbltotbirddata = new Label();
lbltotbirddata.ID = "lbltotbirdata" + i.ToString();
lbltotbirddata.Text = totbirds + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lbltotbirddata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
Label lblmeatyield = new Label();
lblmeatyield.ID = "lblmeatyield" + i.ToString();
lblmeatyield.Text = "<B>Meat Yield in Kgs:</B>" + "&nbsp";
tc.Controls.Add(lblmeatyield);
Label lblmeatyielddata = new Label();
lblmeatyielddata.ID = "lblmeatyied" + i.ToString();
lblmeatyielddata.Text = meatyield + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lblmeatyielddata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
Label lblavgweight = new Label();
lblavgweight.ID = "lblavgweight" + i.ToString();
lblavgweight.Text = "<B>Avg Weight:</B>" + "&nbsp";
tc.Controls.Add(lblavgweight);
Label lblavgweightdata = new Label();
lblavgweightdata.ID = "lblavgweightdata" + i.ToString();
lblavgweightdata.Text = Avgweight + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lblavgweightdata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
DataTable dtdcDetails = new DataTable();
objRetailPL.sno = Convert.ToInt32(dtdate.Rows[i]["sno"].ToString());
dtdcDetails = objRetailBAL.dtdateTallyTable(objRetailPL);
GridView gv = new GridView();
//gv.ID = "gv" + dtdate.Rows[i]["BranchDate"].ToString();
gv.Width = 600;
Label lblTotal = new Label();
Label lbltotaleggs = new Label();
BoundField partyname = new BoundField();
partyname.HeaderText = "PartyName";
partyname.DataField = "partyname";
gv.Columns.Add(partyname);
BoundField birdtype = new BoundField();
birdtype.HeaderText = "Bird Type";
birdtype.DataField = "birdname";
gv.Columns.Add(birdtype);
BoundField totweight = new BoundField();
totweight.HeaderText = "Total Weight";
totweight.DataField = "totalweight";
gv.Columns.Add(totweight);
BoundField rateperkg = new BoundField();
rateperkg.HeaderText = "Rate/Kg";
rateperkg.DataField = "rateperkg";
gv.Columns.Add(rateperkg);
BoundField Bdcno = new BoundField();
Bdcno.HeaderText = "DCNo";
Bdcno.DataField = "dcno";
gv.Columns.Add(Bdcno);
// Here I want to add Button(confirm) In dynamic Gridview..
gv.AutoGenerateColumns = false;
gv.ShowFooter = true;
gv.DataSource = dtdcDetails;
gv.DataBind();
}
}
}
how can i add button control in Dynamic gridview , i tried with Templeate field, but i am not getting exactly output...after how can i add Button Click event for it? please help me?
Thanks in advance...
Sambasiva
You cannot add control dynamically in GridView Control,
You need to create a class and extends it ITemplate.
Following links will explain it
http://www.codedigest.com/Articles/ASPNET/168_Create_Dynamic_GridView_Control_in_C_ASPNet.aspx
http://www.codeproject.com/Articles/13462/How-to-create-template-columns-dynamically-in-a-gr

how to retrieve sheet names into dropdownlist

DataTable dtExcelSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
ArrayList aList = new ArrayList();
foreach (DataRow row in dtExcelSheetName.Rows)
{
aList.Add(row);
}
drpSeletSheet.DataSource = aList;
for (int i = 1; i < dtExcelRecords.Rows.Count + 1; i++)
{
drpSeletSheet.Items.Add(dtExcelRecords.Rows[i]["Table_Name"].ToString());
}
drpSeletSheet.DataBind();
objAdapter1.SelectCommand = cmd;
objAdapter1.Fill(dtExcelRecords);

Find radio button control in nested repeater control in asp.net?

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
}
}
}
}
}
}

Update one cell after adding the new row with same values in gridview

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

Resources