Grid view event not getting triggered - asp.net

I have a gridview created dynamically , now i am trying to do edit each column by keeping a link button. But the rowdatabound event is not getting triggered.Where i might have gone wrong?
Below is my code :
dtValues = gObj.GetAllDocumentsHistoryList();
dtHeader = gObj.GetAllHeaderList();
GridView gvEmployee = new GridView();
gvEmployee.ShowHeaderWhenEmpty = true;
gvEmployee.EmptyDataText = "Sorry No History Records Found !!!!!!!";
gvEmployee.AutoGenerateColumns = false;
for (int i = 0; i < dtValues.Columns.Count; i++)
{
string name = dtValues.Columns[i].ColumnName.ToString();
BoundField boundfield = new BoundField();
boundfield.DataField = dtValues.Columns[i].ColumnName.ToString();
for (int j = 0; j < dtHeader.Rows.Count; j++)
{
if (dtHeader.Rows[j]["ColCode"].ToString() == dtValues.Columns[i].ColumnName.ToString())
{
boundfield.HeaderText = dtHeader.Rows[j]["ColName"].ToString();
if (boundfield.HeaderText.Contains("Date") || boundfield.HeaderText.Contains("DocExpiry"))
{
boundfield.DataFormatString = "{0:dd/MMM/yyyy}";
}
}
else if (dtValues.Columns[i].ColumnName.ToString() == "Last Modified Date")
{
boundfield.HeaderText = "Last Modified Date";
boundfield.DataFormatString = "{0:dd/MMM/yyyy}";
}
}
gvEmployee.Columns.Add(boundfield);
}
gvEmployee.DataSource = dtValues;
gvEmployee.DataBind();
gvEmployee.Width = new Unit("90%");
gvEmployee.RowDataBound += new GridViewRowEventHandler(gvEmployee_RowDataBound);
protected void gvEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[3].Controls.Add(lnkView);
}

Just add your RowDataBound handler before DataBind.
Corrected Code:
gvEmployee.DataSource = dtValues;
gvEmployee.RowDataBound += new GridViewRowEventHandler(gvEmployee_RowDataBound);
gvEmployee.DataBind();
gvEmployee.Width = new Unit("90%");

Related

How to read each row of grid

I am trying to use a tool tip on every row of a grid to show details whenever user place pointer on particular cell. It's supposed to show details for every row but it only shows details for the first row. Can any one help me?
for (int i = 1; i <= e.Row.Cells.Count - 1; i++)
{
if (e.Row.Cells[i].Text == "0" || string.IsNullOrEmpty(e.Row.Cells[i].Text) || e.Row.Cells[i].Text == " ")
{
e.Row.Cells[i].Text = "";
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Blue;
dateSetExport.Tables.Clear();
dateSetExport.Reset();
SqlParameter[] param = new SqlParameter[2];
param[1] = new SqlParameter("#Startdate", gvDetails.HeaderRow.Cells[i].Text);
param[0] = new SqlParameter("#Employe_Id", e.Row.Cells[0].Text.Split('-')[0]);
DataTable dt1 = DataHelper.getDataTableExecuteSP("usp_GetToolTip", param);
dt1.TableName = "ToolTip";
dateSetExport.Tables.Add(dt1);
string tooltip = "";
for (int j = 0; j < dt1.Rows.Count; j++)
{
tooltip = tooltip + dt1.Rows[j]["normal_working_hours"].ToString() + " Hours : " + dt1.Rows[j]["description"].ToString()+"\n\n";
}
e.Row.Cells[i].ToolTip = tooltip;
}
}
You can use another foreach in order to loop all rows :
foreach (GridViewRow row in GridView.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//do your staff
}
}
But for me, you should use GridView_RowDataBound event :
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 1; i <= e.Row.Cells.Count - 1; i++)
{
if (e.Row.Cells[i].Text == "0" || string.IsNullOrEmpty(e.Row.Cells [i].Text) || e.Row.Cells[i].Text == " ")
{
e.Row.Cells[i].Text = "";
}
else
{
e.Row.Cells[i].BackColor = System.Drawing.Color.Blue;
dateSetExport.Tables.Clear();
dateSetExport.Reset();
SqlParameter[] param = new SqlParameter[2];
param[1] = new SqlParameter("#Startdate", gvDetails.HeaderRow.Cells[i].Text);
param[0] = new SqlParameter("#Employe_Id", e.Row.Cells[0].Text.Split('-')[0]);
DataTable dt1 = DataHelper.getDataTableExecuteSP("usp_GetToolTip", param);
dt1.TableName = "ToolTip";
dateSetExport.Tables.Add(dt1);
string tooltip = "";
for (int j = 0; j < dt1.Rows.Count; j++)
{
tooltip = tooltip + dt1.Rows[j]["normal_working_hours"].ToString() + " Hours : " + dt1.Rows[j]["description"].ToString()+"\n\n";
}`enter code here`
e.Row.Cells[i].ToolTip = tooltip;
}
}
}
}

I have to click twice a link button to change page

I have to click linkbutton twice to change the page and load subfolders of current folder. I think I have some problems with my session and event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = Server.MapPath(Session["url"].ToString()).Split(Path.DirectorySeparatorChar);
Table table = new Table();
l.ID = "lable" + table.Rows.Count;
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Add(table);
}
else
{
if(Directory.Exists(Server.MapPath(Session["url"].ToString())))
{
string[] allFolders = Directory.GetDirectories(Server.MapPath(Session["url"].ToString()));
Table table = new Table();
foreach (string str in allFolders)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = str.Split(Path.DirectorySeparatorChar);
l.ID = strarray.Last();
l.CommandName = "createLink";
l.Click+= new EventHandler(LinkButton_Command);
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Add(table);
}
}
else
{
Work work=new Work();
work.SetFolder(Session["url"].ToString());
work.CreateFolder();
}
}
}
public void LinkButton_Command(object sender, EventArgs e)
{
Session["url"] = Session["url"] + "\\" + ((LinkButton)sender).ID;
}
I think this is because the Page_Load() method is called before the LinkButton_Command(). The session variable Session["url"] still contains the previous value when the code in Page_Load() executes.
Try moving the code from the else-branch of Page_Load() at the end of LinkButton_Command().
after mix up your answer and my program , come to a answer that will work.
protected void Page_Load(object sender, EventArgs e)
{
if (Directory.Exists(Server.MapPath(Session["url"].ToString())))
{
string[] allFolders = Directory.GetDirectories(Server.MapPath(Session["url"].ToString()));
Table table = new Table();
foreach (string str in allFolders)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = str.Split(Path.DirectorySeparatorChar);
l.ID = strarray.Last();
l.CommandName = "createLink";
l.Click += new EventHandler(LinkButton_Command);
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Clear();
this.form1.Controls.Add(table);
}
}
}
public void LinkButton_Command(object sender, EventArgs e)
{
Session["url"] = Session["url"] + "\\" + ((LinkButton)sender).ID;
if (Directory.Exists(Server.MapPath(Session["url"].ToString())))
{
string[] allFolders = Directory.GetDirectories(Server.MapPath(Session["url"].ToString()));
Table table = new Table();
foreach (string str in allFolders)
{
TableRow r = new TableRow();
TableCell c1 = new TableCell();
LinkButton l = new LinkButton();
var strarray = str.Split(Path.DirectorySeparatorChar);
l.ID = strarray.Last();
l.CommandName = "createLink";
l.Click += new EventHandler(LinkButton_Command);
l.Text = strarray.Last();
l.EnableViewState = true;
r.ID = "newRow" + table.Rows.Count;
c1.ID = "newC1" + table.Rows.Count;
c1.Controls.Add(l);
r.Cells.Add(c1);
table.Rows.Add(r);
this.form1.Controls.Clear();
this.form1.Controls.Add(table);
}
}
}

Need to Retrieve data from dynamically added text boxes

I added text boxes dynamically in ASP.Net from server side. By using one example which is shown in followed link
http://www.dotnettips4u.com/2013/03/dynamically-creating-text-boxes-using-c.html.
But I couldn't find out how to retrieve values from those text boxes..
Please help me to come out from this..
Here I am posting my code also..
Client Side Code:
<asp:TextBox ID="NoOfPsngr" runat="server" />
<asp:Button ID="AddP" runat="server" Text="Add Passengers" OnClick="AddP_Click" />
<asp:Panel runat="server" ID="passengerdet">
</asp:Panel>
Server Side Code:
protected void AddP_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(NoOfPsngr.Text);
Table table = new Table();
table.ID = "PsngrTbl";
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TableRow row = new TableRow();
TableCell namelblCell = new TableCell();
Label namelbl = new Label();
namelbl.Text = "Name";
TableCell nameTxtCell = new TableCell();
TextBox nameTxt = new TextBox();
TableCell typelblCell = new TableCell();
Label typelbl = new Label();
typelbl.Text = "Type";
TableCell typeSelectCell = new TableCell();
DropDownList typeSelect = new DropDownList();
ListItem adultItem = new ListItem();
adultItem.Text = "Adult";
adultItem.Value = "Adult";
typeSelect.Items.Add(adultItem);
ListItem childItem = new ListItem();
childItem.Text = "Child";
childItem.Value = "Child";
typeSelect.Items.Add(childItem);
ListItem infantItem = new ListItem();
infantItem.Text = "Infant";
infantItem.Value = "Infant";
typeSelect.Items.Add(infantItem);
TableCell etktlblCell = new TableCell();
Label etktlbl = new Label();
etktlbl.Text = "Eticket No";
TableCell etktTxtCell = new TableCell();
TextBox etktTxt = new TextBox();
//Adding.....
namelblCell.Controls.Add(namelbl);
typelblCell.Controls.Add(typelbl);
etktlblCell.Controls.Add(etktlbl);
nameTxtCell.Controls.Add(nameTxt);
typeSelectCell.Controls.Add(typeSelect);
etktTxtCell.Controls.Add(etktTxt);
nameTxt.ID = "PName" + i;
typeSelect.ID = "PType" + i;
etktTxt.ID = "ETkt" + i;
row.Controls.Add(namelblCell);
row.Controls.Add(nameTxtCell);
row.Controls.Add(typelblCell);
row.Controls.Add(typeSelectCell);
row.Controls.Add(etktlblCell);
row.Controls.Add(etktTxtCell);
table.Rows.Add(row);
}
passengerdet.Controls.Add(table);
}
use javascript like
$('#PsngrTbl').find('input[type=radio]').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue;
var controlName = $(this).attr('name');
if ($('[name=' + controlName + ']:checked').val() == undefined) {
oValue = "";
}
else {
oValue = $('[name=' + controlName + ']:checked').val();
}
});
$('#PsngrTbl').find('input[type=checkbox]').each(function (index, element) {
var o = $(this);
var value;
if (o.on == true) {
value = 1;
}
else {
value = 0;
}
var oID = o.attr("id");
var oValue = value;
});
$('#PsngrTbl').find('textarea').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
$('#PsngrTbl').find('select').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
It will return all values of controlls of that table

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

Gridview Sort Causing RowDataBound to not function correctly

I have a gridview that works just fine with each of my row commands, however, once it is sorted it causes the rowdatabound event to use incorrect values rather than the actual values in the row after it has been sorted. Any help would be appreciated!
Here is my code behind.
//Verify and Update Record
protected void UnverifiedSalesGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
buttonCommand = e.CommandName;
MessageLBL.Text = "";
if (e.CommandName == "VerifyRecord")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID != "38")
{
verifyRenewal = false;
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
//Get row index.
UnverifiedSalesGV.SetEditRow(Convert.ToInt32(e.CommandArgument));
verifyRenewal = true;
}
}
if (e.CommandName == "UpdateProduct")
{
DropDownList productValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("RenewalProductDDL");
if (productValue.SelectedIndex != 0)
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET ProductID = #ProductID, Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["ProductID"].DefaultValue = productValue.SelectedValue;
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Please select renewal type.";
}
}
if (e.CommandName == "UpdateRecord")
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("CommissionMonthDDL");
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateCommand = "UPDATE [Sales] SET [GrossSalesAmount] = #GrossSalesAmount, [NetSalesAmount] = #NetSalesAmount, [Notes] = #Notes, [CommissionMonth] = #CommissionMonth, [DateLastModified] = #DateLastModified, [UserLastModified] = #UserLastModified WHERE [ID] = #ID";
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UnverifiedSalesSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}
}
//Get product
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
if (buttonCommand == "VerifyRecord")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
}
}
}
}
I was finally able to solve my problem by hardcoding in the following:
//Hide and show fields
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == rowIndex)
{
string state = e.Row.RowState.ToString();
if (state == "Alternate, Edit" || state == "Edit")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
Label accountManagerLBL = (Label)e.Row.FindControl("AccountManagerLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
DropDownList accountManagerDDL = (DropDownList)e.Row.FindControl("AccountManagerDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
Label notesLBL = (Label)e.Row.FindControl("NotesLBL");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
accountManagerLBL.Visible = true;
accountManagerDDL.Visible = false;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
notesLBL.Visible = true;
}
}
}
}

Resources