edit row in Gridview by button - c#

I have a Gridview like this
<div id="gridScroll" style="width: 100%; height: calc(100vh - 310px); overflow: auto">
<asp:GridView ID="gridRoles" runat="server" Width="100%" AutoGenerateColumns="False" Font-Names="Arial" PageSize="12"
Font-Size="11pt" CssClass="textGrid" AlternatingRowStyle-BackColor="#CED8F6" HeaderStyle-BackColor="#F2F2F2"
AllowPaging="True" OnPageIndexChanged ="IndexChanged" OnPageIndexChanging ="PageChange" OnRowDataBound="gridroles_RowDataBound" OnRowEditing="editRow">
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" text="Edit" OnCliendClick="btnEditClick()" />
<asp:Button ID="btnAdd" runat="server" text="Add" OnClientClick="btnAddClick()" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="First Name" HeaderText="First Name" />
<asp:BoundField DataField="Last Name" HeaderText="Last Name" /
</Columns>
<HeaderStyle BackColor="#A9BCF5" />
<AlternatingRowStyle BackColor="#CED8F6" />
</asp:GridView>
</div>
The data is bound from the back end
DataTable dt = new DataTable();
dt.Columns.Add("Action");
dt.Columns.Add("First Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
for (int i = 0; i < credentials.Count; i++)
{
DataRow row1 = dt.NewRow();
row1["First Name"] = credentials[i].FirstName.ToString();
row1["Last Name"] = credentials[i].LastName.ToString();
dt.Rows.Add(row1);
}
DataRow row2 = dt.NewRow();
dt.Rows.Add(row2);
gridRoles.DataSource = dt;
gridRoles.DataBind();
I have this method btnEditClick() that is called when the Edit button is clicked.
function btnEditClick() {
var target = event.target || event.srcElement;
target.id = "btnEdit";
target.style.display = 'none';
var cancel = document.getElementById("btnCancel");
if (cancel != null)
cancel.click();
var row = target.parentElement.parentElement;
var cells = row.cells;
var hdn = document.createElement("input");
hdn.type = "hidden";
hdn.id = "hdnId";
hdn.name = "hdnId";
hdn.value = cells[1].innerHTML;
cells[0].appendChild(hdn);
for (var i = 2; i < 11; i++) {
//2, 3,4 , 10 textboxes
if (i == 2 || i == 3 || i == 4 || i == 10) {
var txt = document.createElement("input");
txt.value = cells[i].innerHTML;
txt.alt = cells[i].innerHTML;
txt.name = "txt" + i;
txt.maxLength = 50;
txt.style.width = "95%";
cells[i].innerHTML = "";
cells[i].appendChild(txt);
}
//this is for a dropdownlist for other columns in gridview I will add
if (i >= 5 && i < 10) {
var ddl = document.createElement("select");
var option = document.createElement("option");
option.setAttribute("value", "TRUE");
option.innerHTML = "TRUE";
ddl.appendChild(option);
var option2 = document.createElement("option");
option2.setAttribute("value", "FALSE");
option2.innerHTML = "FALSE";
ddl.appendChild(option2);
if (cells[i].innerHTML == "False") {
ddl.selectedIndex = 1;
}
ddl.name = "DDL" + i;
ddl.alt = cells[i].innerHTML;
cells[i].innerHTML = "";
cells[i].appendChild(ddl);
}
}
var btnCancel = document.createElement("button");
var Confirm = document.getElementById("cph_body_btnConfirm");
btnCancel.textContent = "Cancel";
btnCancel.id = "btnCancel";
btnCancel.onclick = cancelClick;
cells[0].appendChild(Confirm);
cells[0].appendChild(btnCancel);
return false;
The problem is, when I click the edit button it appears to go into edit mode. All the correct textboxes and dropdownlists show up but after about a second it disappears and the row goes back to what it looked like before the button was clicked. I'm not sure if the Gridview is refreshing itself. What would cause this problem?

Related

How to read dynamically added texbox's value in gridview

I need to create dynamic form, which i will have to create the textbox, textarea,dropdown etc, based on the field type.
Now, I have successfully created this dynamic textbox etc using my rowdatabound.
My problem is I could not retrieve the textbox value entered when the save button is clicked.
My aspx file
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="selectProspect" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FieldTitle" HeaderText="" />
<asp:BoundField DataField="FieldType" HeaderText="FieldType" />
<asp:TemplateField>
<ItemTemplate>
//DYNAMICALLY ADDING TEXTBOX
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RightText" HeaderText="" />
<asp:BoundField DataField="TemplatesInfoCode" HeaderText="TemplatesInfoCode" ItemStyle-CssClass="hiddencol" />
</Columns>
</asp:GridView>
My code behind file
protected void Page_Load(object sender, EventArgs e)
{
GetTemplateComponent();
}
public void GetTemplateComponent()
{
StringBuilder sb;
DataSet ds;
sb = new StringBuilder();
sb.AppendLine("select * from template where tc='0002' order by Sequence");
ds = Conn.DataAdapter(CommandType.Text, sb.ToString());
gv.DataSource = ds;
gv.DataBind();
}
protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string value = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "FieldType"));
if (value == "Date" || value == "TextBox")
{
TextBox TextBox1 = new TextBox() { ID = "TextBox1", EnableViewState = false, CssClass = "form-control" };
e.Row.Cells[3].Controls.Add(TextBox1);
}
if (value == "TextArea")
{
TextBox DateTextBox = new TextBox() { EnableViewState = false, CssClass = "form-control", TextMode = TextBoxMode.MultiLine, Rows = 5, Columns = 50 };
e.Row.Cells[3].Controls.Add(DateTextBox);
}
if (value == "Content")
{
TextBox ContentAreaControl = new TextBox()
{
TextMode = TextBoxMode.MultiLine,
EnableViewState = false,
Columns = 10,
MaxLength = 150,
Height = 200,
CssClass = "Content-container",
};
e.Row.Cells[3].Controls.Add(ContentAreaControl);
}
}
}
protected void SaveTemplateDetails(object sender, EventArgs e)
{
foreach (GridViewRow row in gv.Rows)
{
FieldValue.Value = row.Cells[3].Text.ToString();
*//I DONT KNOW HOW TO READ THE VALUE*
}
}
I just want to know how is the proper way to read this dynamically created textbox
Thank you
ASPX Page Code.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDataBound="gv_RowDataBound1">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="selectProspect" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FieldTitle" HeaderText="" />
<asp:BoundField DataField="FieldType" HeaderText="FieldType" />
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RightText" HeaderText="" />
<asp:BoundField DataField="TemplatesInfoCode" HeaderText="TemplatesInfoCode" />
</Columns>
</asp:GridView>
Code behind file
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string fieldType = e.Row.Cells[2].Text;
TextBox txtData = e.Row.Cells[3].FindControl("TextBox1") as TextBox;
switch (fieldType)
{
case "Date":
case "TextBox":
txtData.EnableViewState = false;
txtData.CssClass = "form-control";
break;
case "TextArea":
txtData.EnableViewState = false;
txtData.CssClass = "form-control";
txtData.TextMode = TextBoxMode.MultiLine;
txtData.Rows = 5;
txtData.Columns = 50;
break;
case "Content":
txtData.TextMode = TextBoxMode.MultiLine;
txtData.EnableViewState = false;
txtData.Columns = 10;
txtData.MaxLength = 150;
txtData.Height = 200;
txtData.CssClass = "Content-container";
break;
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveTemplateDetails();
}
private void SaveTemplateDetails()
{
foreach (GridViewRow row in gv.Rows)
{
foreach (Control c in row.Cells[3].Controls)
{
TextBox txtDate = c as TextBox;
if (txtDate != null)
{
string data = txtDate.Text;
}
}
}
}

Why Asp:GridView calls button click method in server side?

In my case i have asp:gridview with OnRowCommand calls server method but when i try to refresh my page manually then it also calls OnRowCommand method, i don't know where is the actual problem.
My Code:.aspx
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnSelectedIndexChanged="CUG_OnSelectedIndexChanged" OnRowCommand="CugSubmit_onserverclick1" EnableViewState="true"BorderStyle="Solid" BorderColor="Gray" BorderWidth="1px" EditRowStyle-BorderStyle="Solid" EditRowStyle-BorderWidth="1px" EditRowStyle-BorderColor="Gray" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="Gray" RowStyle-BorderStyle="Solid" RowStyle-BorderColor="Gray" RowStyle-BorderWidth="1px" EmptyDataRowStyle-BorderStyle="Solid" EmptyDataRowStyle-BorderColor="Black" EmptyDataRowStyle-BorderWidth="1px" SortedAscendingHeaderStyle-BorderStyle="Solid" SortedAscendingHeaderStyle-BorderColor="Black" SortedAscendingHeaderStyle-BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Driver ID">
<ItemTemplate>
<asp:Label ID="lbl_Dri_Name" runat="server" Text='<%# Eval("VehicleNo") %>' Visible="false"></asp:Label>
<asp:TextBox ID="Dri_Name" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dedicated">
<ItemTemplate>
<asp:Label ID="lbl_Vehitype" runat="server" Text='<%# Eval("VehicleType") %>' Visible="false"></asp:Label>
<asp:CheckBox ID="Vehitype" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="ProcessThis" Text="Submit" />
<asp:ButtonField CommandName="Select" ItemStyle-Width="30" Text="delete" HeaderText="Delete" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
</ItemTemplate>
<FooterStyle HorizontalAlign="left" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns></asp:gridview>
My code:.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetCUGList();
}
}
protected void CugSubmit_onserverclick1(object sender, GridViewCommandEventArgs e)
{
DL.CustomerProfile ObjInput = new CustomerProfile();
BL.CustomerInputBL ObjCustomerInputBL = new CustomerInputBL();
if (e.CommandName == "ProcessThis")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.VehiNo = textBox.Text;
ObjInput.Update = "Insert";
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*****/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Insert Request Sent to Admin')", true);
GetCUGList();
}
}
AddNewRowToGrid();
}
else if (e.CommandName == "ProcessThisUpdate")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.Update = "Update";
ObjInput.VehiNo = textBox.Text;
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*******/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Update Request Sent to Admin')", true);
GetCUGList();
}
}
}
}

DataTable in ViewState is Returning Deleted Rows

I am currently working on a dynamic gridview that will allow a user to add or delete rows in order to be saved as database entries later on.
My gridview markup is as such:
<asp:UpdatePanel ID="upAirporterSchedule" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvAirporterSchedule" runat="server" ShowFooter="true" AutoGenerateColumns="false" CssClass="table table-striped table-bordered table-hover dataTable no-footer" OnRowDataBound="gvAirporterSchedule_RowDataBound" OnRowCommand="gvAirporterSchedule_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Location" ItemStyle-Width="25%">
<ItemTemplate>
<asp:DropDownList ID="ddlScheduleLoc" runat="server" CssClass="form-control"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Start Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterStartDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("StartDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterEndDate" runat="server" CssClass="form-control date-picker" Text='<%# Eval("EndDateColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Departure Time">
<ItemTemplate>
<div class="input-group">
<asp:TextBox ID="tbxAirporterDepTime" runat="server" CssClass="form-control time-picker" Text='<%# Eval("DeptTimeColumn") %>'></asp:TextBox>
<span class="input-group-addon">
<i class="fa fa-clock-o"></i>
</span>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Duration">
<ItemTemplate>
<asp:TextBox ID="tbxAirporterDuration" runat="server" CssClass="form-control" Text='<%# Eval("DurationColumn") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button ID="btnDel" runat="server" CssClass="btn btn-default" Text="Delete" CommandName="DeleteRow" />
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-default" Text="Add Entry" CommandName="AddRow" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Aside from this grid, I have some other fields in the user control. When I go to save, the user will click a button at the bottom of the user control which will package up the form fields above it and the grid into some classes and shoot this off to the database code to add/update this data.
Page.Validate("AirporterFares");
if (Page.IsValid)
{
try
{
// Save trip information.
SysVarService.SharedRideTrip trip = new SysVarService.SharedRideTrip();
if (_tripID > 0)
trip = Global.sysVarService.GetSharedRideTripByID(_tripID);
trip.isVisible = 1;
trip.productType = ReservationService.ProductType.TOUR;
trip.originStopID = Convert.ToInt32(ddlOrigin.SelectedValue.ToString());
trip.destinationStopID = Convert.ToInt32(ddlDestination.SelectedValue.ToString());
trip.defaultDuration = 0;
trip.effectiveDate = DateTime.Parse(tbxAirporterEffDate.Text.Trim());
trip.startTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
trip.endTimeOfDay = new DateTime(trip.effectiveDate.Year, trip.effectiveDate.Month, trip.effectiveDate.Day, 1, 1, 1);
// Save the two fare information.
SysVarService.SharedRideTrip_ShuttleFare aFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 1,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterAdultFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
SysVarService.SharedRideTrip_ShuttleFare cFare = new SysVarService.SharedRideTrip_ShuttleFare()
{
effectiveDate = trip.effectiveDate,
effectiveTravelDate = trip.effectiveDate,
paxTypeID = 2,
oneWayCost = Foundation.StringFormatter.currencyToDouble(tbxAirporterChildFare.Text.Trim()),
returnCost = 0.00,
numPax = 1,
Currency = 0
};
string status = "";
if (_updating)
status = Global.sysVarService.UpdateAirporterFare(trip, aFare, cFare, GetScheduleEntries());
else
status = Global.sysVarService.AddAirporterFare(trip, aFare, cFare, GetScheduleEntries());
if (!String.IsNullOrEmpty(status))
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = status;
return;
}
}
catch (Exception ex)
{
spanErrorMsg.Visible = true;
spanErrorMsg.InnerText = ex.ToString();
return;
}
Response.Redirect("~/Internal/Admin/Default.aspx?action=Airporter_Fares");
}
When I go to either add or update, I call GetScheduledEntries, which is supposed to loop through the datatable (grabbing it from the viewstate) and convert the templated fields into object properties and stuff these objects in a list.
private List<AdminConfigService.SharedRideTimes> GetScheduleEntries()
{
int idx = 0;
List<AdminConfigService.SharedRideTimes> schedule = new List<AdminConfigService.SharedRideTimes>();
if (gvAirporterSchedule.Rows.Count >= 1)
{
for (int i = 1; i <= gvAirporterSchedule.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
schedule.Add(new AdminConfigService.SharedRideTimes()
{
StartDate = DateTime.Parse(startDate.Text.Trim()),
EndDate = DateTime.Parse(endDate.Text.Trim()),
DepartureTime = DateTime.Parse(deptTime.Text.Trim()),
Duration = Convert.ToInt32(duration.Text.Trim()),
EffectiveDates = "",
StopID = Convert.ToInt32(ddl.SelectedValue.ToString())
});
idx++;
}
return schedule;
}
else
return schedule;
}
The problem is, if I delete rows from this grid view and then attempt to save the form, the datatable from the viewstate is bringing back those deleted rows and acting like they are still existing for saving, even though the gridview and the datatable do not have that row anymore (when the DeleteRow command goes through).
else if (e.CommandName == "DeleteRow")
{
SetRowData();
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
int idx = gvr.RowIndex;
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[idx]);
currentRow = dt.NewRow();
ViewState["AirporterScheduleTable"] = dt;
gvAirporterSchedule.DataSource = dt;
gvAirporterSchedule.DataBind();
SetPreviousData();
}
}
}
private void SetPreviousData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable dt = (DataTable)ViewState["AirporterScheduleTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
ddl.SelectedValue = dt.Rows[i]["LocColumn"].ToString();
startDate.Text = dt.Rows[i]["StartDateColumn"].ToString();
endDate.Text = dt.Rows[i]["EndDateColumn"].ToString();
deptTime.Text = dt.Rows[i]["DeptTimeColumn"].ToString();
duration.Text = dt.Rows[i]["DurationColumn"].ToString();
idx++;
}
}
}
}
private void SetRowData()
{
int idx = 0;
if (ViewState["AirporterScheduleTable"] != null)
{
DataTable current = (DataTable)ViewState["AirporterScheduleTable"];
DataRow currentRow = null;
if (current.Rows.Count > 0)
{
for (int i = 1; i <= current.Rows.Count; ++i)
{
// Get data controls.
DropDownList ddl = (DropDownList)gvAirporterSchedule.Rows[idx].Cells[0].FindControl("ddlScheduleLoc");
TextBox startDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[1].FindControl("tbxAirporterStartDate");
TextBox endDate = (TextBox)gvAirporterSchedule.Rows[idx].Cells[2].FindControl("tbxAirporterEndDate");
TextBox deptTime = (TextBox)gvAirporterSchedule.Rows[idx].Cells[3].FindControl("tbxAirporterDepTime");
TextBox duration = (TextBox)gvAirporterSchedule.Rows[idx].Cells[4].FindControl("tbxAirporterDuration");
currentRow = current.NewRow();
current.Rows[i - 1]["LocColumn"] = ddl.SelectedValue;
current.Rows[i - 1]["StartDateColumn"] = startDate.Text;
current.Rows[i - 1]["EndDateColumn"] = endDate.Text;
current.Rows[i - 1]["DeptTimeColumn"] = deptTime.Text;
current.Rows[i - 1]["DurationColumn"] = duration.Text;
idx++;
}
ViewState["AirporterScheduleTable"] = current;
}
}
}
There doesn't seem to be any where in the code that I am not updating the ViewState datatable when I either delete or add entries to this dynamic gridview. What could be causing the difference in ViewStates? Does the full postback of the button outside of the UpdatePanel and GridView have a different ViewState?
I also pretty much followed this tutorial exactly.
Turned out to be one of those cases where you overlook something simple. When I was populating the grid with data on load, I did not protect it with a
if (!Page.IsPostback)
Because of that, every time the row was deleted, it would refill the data table with the data on Page Load and cause the weird issues where deleted rows didn't seem to be getting deleted.

Check for column and bind grid if exists or not

How to bind data to itemtemplate of gridview at RowDataBound event. I am using a gridview and below is the code for that grid view.
<asp:GridView ID="gvCoreUtilization" runat="server" BackColor="White" BorderColor="#cEcFcE"
BorderStyle="Solid" BorderWidth="1px" CellPadding="4" ForeColor="Black" OnRowCreated="grdPivot3_RowCreated"
AutoGenerateColumns="false" OnRowDataBound="grdCoreUtilization_RowDataBound">
<RowStyle BackColor="#F7F7DE" />
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblRoleID" Text='<%#Eval("RoleId") %>' runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
SupervisorName
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSupervisorName" Text='<%#Eval("SupervisorName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
UserECode
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblUserECode" Text='<%#Eval("UserECode") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
UserName
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblUserName" Text='<%#Eval("UserName") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Designation
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDesignation" Text='<%#Eval("Designation") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
L & D Training%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblLDTraining" Text='<%#Eval("L & D Training%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Non Production%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNonProduction" Text='<%#Eval("Non Production%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Process Support%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProcessSupport" Text='<%#Eval("Process Support%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Process Training%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProcessTraining" Text='<%#Eval("Process Training%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Production%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProduction" Text='<%#Eval("Production%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
System Downtime%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblSystemDowntime" Text='<%#Eval("System Downtime%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Grand Total%
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblGrandTotal" Text='<%#Eval("Grand Total%") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here i want to remove EVAl for binding the data to itemtemplate. In place of this i want to check weather
If all the Column exists in the dataset/Datatable or not which is mentioned in the Gridview.
If all Column exists then bind that column to appropriate Itemtemplate .
If All column not exist then display and bind only available column and hide the not available column.
Query used:-
Select RoleId,SuperVisorName,Userecode,Username,Designation,TimeSpent,ActivityName
from CoreUtilizationForRole1 where roleid=3
After executing the above query, i am doing a pivot on Activity column from c# and those columns are "L & D Training%","Non Production%","Process Support%","Process Training%","Production%","System Downtime%","Grand Total%" which i am binding on ItemTemplate.
Try this on each of your template field.
Set Visible property as following...
Visible='<%# !String.IsNullOrEmpty(Eval("RoleId").ToString()) %>'
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.Label lblRoleNo = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblRoleId");
System.Web.UI.WebControls.Label lblSupervisorName = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblSupervisorName");
System.Web.UI.WebControls.Label lblUserECode = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblUserECode");
System.Web.UI.WebControls.Label lblUserName = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblUserName");
System.Web.UI.WebControls.Label lblDesignation = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblDesignation");
System.Web.UI.WebControls.Label lblLDTraining = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblLDTraining");
System.Web.UI.WebControls.Label lblNonProduction = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblNonProduction");
System.Web.UI.WebControls.Label lblProcessSupport = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblProcessSupport");
System.Web.UI.WebControls.Label lblProcessTraining = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblProcessTraining");
System.Web.UI.WebControls.Label lblProduction = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblProduction");
System.Web.UI.WebControls.Label lblSystemDowntime = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblSystemDowntime");
System.Web.UI.WebControls.Label lblGrandTotal = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblGrandTotal");
//Checking weather Columns exist in the Pivot or not
var dataRow = (DataRowView)e.Row.DataItem;
var columnNameToCheck = "L & D Training%";
var checkTraining = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheck, StringComparison.InvariantCultureIgnoreCase));
if (checkTraining)
{
// Property available
lblLDTraining.Text = (DataBinder.Eval(e.Row.DataItem, "L & D Training%")).ToString();
}
else
{
lblLDTraining.Visible = false;
}
var columnNonProduction = "Non Production%";
var checkNonProduction = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNonProduction, StringComparison.InvariantCultureIgnoreCase));
if (checkNonProduction)
{
// Property available
lblNonProduction.Text = (DataBinder.Eval(e.Row.DataItem, "Non Production%")).ToString();
}
else
{
lblNonProduction.Visible = false;
}
var columnProcessSupport = "Process Support%";
var checkProcessSupport = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnProcessSupport, StringComparison.InvariantCultureIgnoreCase));
if (checkProcessSupport)
{
// Property available
lblProcessSupport.Text = (DataBinder.Eval(e.Row.DataItem, "Process Support%")).ToString();
}
else
{
lblProcessSupport.Visible = false;
}
var columnProcessTraining = "Process Training%";
var checkProcesstraining = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnProcessTraining, StringComparison.InvariantCultureIgnoreCase));
if (checkProcesstraining)
{
// Property available
lblProcessTraining.Text = (DataBinder.Eval(e.Row.DataItem, "Process Training%")).ToString();
}
else
{
lblProcessTraining.Visible = false;
}
var columnProduction = "Production%";
var checkProduction = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnProduction, StringComparison.InvariantCultureIgnoreCase));
if (checkProduction)
{
// Property available
lblProduction.Text = (DataBinder.Eval(e.Row.DataItem, "Production%")).ToString();
}
else
{
lblProduction.Visible = false;
}
var columnSystemDownTime = "System Downtime%";
var checkSystemDownTime = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnSystemDownTime, StringComparison.InvariantCultureIgnoreCase));
if (checkSystemDownTime)
{
// Property available
lblSystemDowntime.Text = (DataBinder.Eval(e.Row.DataItem, "System Downtime%")).ToString();
}
else
{
lblSystemDowntime.Visible = false;
}
var columnGrandTotal = "Grand Total%";
var checkGrandTotal = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnGrandTotal, StringComparison.InvariantCultureIgnoreCase));
if (checkGrandTotal)
{
// Property available
lblGrandTotal.Text = (DataBinder.Eval(e.Row.DataItem, "Grand Total%")).ToString();
}
else
{
lblGrandTotal.Visible = false;
}
var columnNameToCheckRoleID = "RoleId";
var checkRoleID = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckRoleID, StringComparison.InvariantCultureIgnoreCase));
if (checkRoleID)
{
// Property available
lblRoleNo.Text = (DataBinder.Eval(e.Row.DataItem, "RoleId")).ToString();
}
else
{
lblRoleNo.Visible = false;
}
var columnNameToCheckSupervisorName = "SupervisorName";
var checkSupervisorName = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckSupervisorName, StringComparison.InvariantCultureIgnoreCase));
if (checkSupervisorName)
{
// Property available
lblSupervisorName.Text = (DataBinder.Eval(e.Row.DataItem, "SupervisorName")).ToString();
}
else
{
lblSupervisorName.Visible = false;
}
var columnNameToCheckUserECode = "UserECode";
var checkUserECode = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckUserECode, StringComparison.InvariantCultureIgnoreCase));
if (checkUserECode)
{
// Property available
lblUserECode.Text = (DataBinder.Eval(e.Row.DataItem, "UserECode")).ToString();
}
else
{
lblUserECode.Visible = false;
}
var columnNameToCheckUserName = "UserName";
var checkUserName = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckUserName, StringComparison.InvariantCultureIgnoreCase));
if (checkUserName)
{
// Property available
lblUserName.Text = (DataBinder.Eval(e.Row.DataItem, "UserName")).ToString();
}
else
{
lblUserName.Visible = false;
}
var columnNameToCheckDesignation = "Designation";
var checkDesignation = dataRow.Row.Table.Columns.Cast<DataColumn>().Any(x => x.ColumnName.Equals(columnNameToCheckDesignation, StringComparison.InvariantCultureIgnoreCase));
if (checkDesignation)
{
// Property available
lblDesignation.Text = (DataBinder.Eval(e.Row.DataItem, "Designation")).ToString();
}
else
{
lblDesignation.Visible = false;
}
//Changing color of the Pivot Data
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 2)
{
e.Row.BackColor = System.Drawing.Color.GreenYellow;
}
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 3)
{
e.Row.BackColor = System.Drawing.Color.Cyan;
}
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 4)
{
e.Row.BackColor = System.Drawing.Color.Orange;
}
if (Convert.ToInt32(lblRoleNo.Text.ToString()) == 5)
{
e.Row.BackColor = System.Drawing.Color.Pink;
}
}
this code provide you to hide particular cell from code behind if the value is blank...
Protected Sub gvCoreUtilization_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvCoreUtilization.RowDataBound
Try
If e.Row.RowType = DataControlRowType.DataRow Then
Dim olblRoleID As New Label
Dim olblSupervisorName As New Label
Dim olblUserECode As New Label
Dim olblUserName As New Label
Dim olblDesignation As New Label
Dim olblLDTraining As New Label
Dim olblNonProduction As New Label
Dim olblProcessSupport As New Label
Dim olblProcessTraining As New Label
Dim olblProduction As New Label
Dim olblSystemDowntime As New Label
Dim olblGrandTotal As New Label
olblRoleID = CType(e.Row.FindControl("lblRoleID"), Label)
olblSupervisorName = CType(e.Row.FindControl("lblSupervisorName"), Label)
olblUserECode = CType(e.Row.FindControl("lblUserECode"), Label)
olblUserName = CType(e.Row.FindControl("lblUserName"), Label)
olblDesignation = CType(e.Row.FindControl("lblDesignation"), Label)
olblLDTraining = CType(e.Row.FindControl("lblLDTraining"), Label)
olblNonProduction = CType(e.Row.FindControl("lblNonProduction"), Label)
olblProcessSupport = CType(e.Row.FindControl("lblProcessSupport"), Label)
olblProcessTraining = CType(e.Row.FindControl("lblProcessTraining"), Label)
olblProduction = CType(e.Row.FindControl("lblProduction"), Label)
olblSystemDowntime = CType(e.Row.FindControl("lblSystemDowntime"), Label)
olblGrandTotal = CType(e.Row.FindControl("lblGrandTotal"), Label)
If CType(DataBinder.Eval(e.Row.DataItem, "RoleId"), String) = "" Then
olblRoleID.Visible = False
Else
olblRoleID.Text = DataBinder.Eval(e.Row.DataItem, "RoleId")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "SupervisorName"), String) = "" Then
olblSupervisorName.Visible = False
Else
olblSupervisorName.Text = DataBinder.Eval(e.Row.DataItem, "SupervisorName")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "UserECode"), String) = "" Then
olblUserECode.Visible = False
Else
olblUserECode.Text = DataBinder.Eval(e.Row.DataItem, "UserECode")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "UserName"), String) = "" Then
olblUserName.Visible = False
Else
olblUserName.Text = DataBinder.Eval(e.Row.DataItem, "UserName")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Designation"), String) = "" Then
olblDesignation.Visible = False
Else
olblDesignation.Text = DataBinder.Eval(e.Row.DataItem, "Designation")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "L & D Training"), String) = "" Then
olblLDTraining.Visible = False
Else
olblLDTraining.Text = DataBinder.Eval(e.Row.DataItem, "L & D Training")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Non Production"), String) = "" Then
olblNonProduction.Visible = False
Else
olblNonProduction.Text = DataBinder.Eval(e.Row.DataItem, "Non Production")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Process Support"), String) = "" Then
olblProcessSupport.Visible = False
Else
olblProcessSupport.Text = DataBinder.Eval(e.Row.DataItem, "Process Support")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Process Training"), String) = "" Then
olblProcessTraining.Visible = False
Else
olblProcessTraining.Text = DataBinder.Eval(e.Row.DataItem, "Process Training")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Production"), String) = "" Then
olblProduction.Visible = False
Else
olblProduction.Text = DataBinder.Eval(e.Row.DataItem, "Production")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "System Downtime"), String) = "" Then
olblSystemDowntime.Visible = False
Else
olblSystemDowntime.Text = DataBinder.Eval(e.Row.DataItem, "System Downtime")
End If
If CType(DataBinder.Eval(e.Row.DataItem, "Grand Total"), String) = "" Then
olblGrandTotal.Visible = False
Else
olblGrandTotal.Text = DataBinder.Eval(e.Row.DataItem, "Grand Total")
End If
End If
Catch ex As Exception
General.LogException(ex)
End Try
End Sub
And if you want to hide entire column in grid please follow below step
1) Create View state property on page for every column
Property RoleId() As boolen
Get
If IsNothing(Me.ViewState("RoleId")) Then Me.ViewState("RoleId") = false
Return CType(Me.ViewState("RoleId"), Boolean)
End Get
Set(ByVal value As Boolean)
Me.ViewState("RoleId") = value
End Set
End Property
2) Loop throw Data-set for every column for each row and check value exist or not and set this property ,finally you have property with value true or false and you can find which column need to display in grid.
3)then you can easily hide column of grid.
if Me.RoleId= True then
'Write code to Display
else
'Write code to Hide
end if

how to access the textbox of dynamically created table in user control page?

Actually i'm creating web template using asp.net and c#.
in my user control page i have to create the table dynamically. i just read the data from XML file then retrieve the name and number of columns and rows of each table. while i'm creating the table i assign the name and id to each cell. because i have one row including some textbox for adding the data to database. but after i have created the table i can not access to the textbox cells based on id to get their data and insert it to database.
my dynamic table code is:
public void CreateAddDynamicTable()
{
XmlDocument xDocRead = new XmlDocument();
xDocRead.Load(Server.MapPath("ModuleTemp.xml"));
string xModuleName = hid_ChooseModule.Value;
XmlNode xColCounter = xDocRead.SelectSingleNode("ModuleTemp/" + xModuleName + "/List");
int colCount = xColCounter.ChildNodes.Count;
int nonPkCounter = 0;
string[] nonPrimaryKey = new string[100];
string[] nonPkNewDataTemp = new string[100];
for (int i = 1; i <= colCount; i++)
{
if (xDocRead.SelectSingleNode("ModuleTemp/" + xModuleName + "/Add/TableColumn" + i).Attributes.GetNamedItem("IsPrimaryKey").Value == "N")
{
nonPrimaryKey[nonPkCounter] = xDocRead.SelectSingleNode("ModuleTemp/" + xModuleName + "/Add/TableColumn" + i).Attributes.GetNamedItem("Name").Value;
nonPkCounter++;
}
}
ph_Uc_AddModule.Controls.Clear();
// Fetch the number of Rows and Columns for the table
// using the properties
int tblRows = nonPkCounter;
int tblCols = 2;
// Create a Table and set its properties
Table tbl = new Table();
// Add the table to the placeholder control
ph_Uc_AddModule.Controls.Add(tbl);
// Now iterate through the table and add your controls
for (int i = 0; i < tblRows; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < tblCols; j++)
{
TableCell tc = new TableCell();
Label td_Add_Header = new Label();
TextBox td_Add = new TextBox();
if (j == 0)
{
td_Add_Header.Text = nonPrimaryKey[i];
td_Add_Header.ID = "lb" + (i + 1) + "_header_AddModule";
// Add the control to the TableCell
tc.Controls.Add(td_Add_Header);
tc.CssClass = "td_Header_AddModule";
}
else
{
td_Add.Text = "";
td_Add.ID = "tb" + (i + 1) + "_AddModule";
// Add the control to the TableCell
tc.Controls.Add(td_Add);
tc.CssClass = "td_Tb_AddModule";
}
// Add the TableCell to the TableRow
tr.Cells.Add(tc);
}
// Add the TableRow to the Table
tbl.Rows.Add(tr);
}
}
my user control page which is contain a PlaceHolder is as below:
<asp:Panel ID="pn_Uc_TModule" runat="server">
<asp:Table runat="server" ID="table_Uc_TModule" CssClass="table_Uc_TModule" Width="100%">
<asp:TableRow runat="server" VerticalAlign="Top" Height="50px">
<asp:TableCell runat="server">
<asp:Button runat="server" Text="" CssClass="btn_Add_Active" OnClick="btn_AddNew_Click" />
<asp:Button ID="btn_Cancel_NewItem" runat="server" Text="" CssClass="btn_Cancel_New" OnClick="btn_Cancel_AddNew" Visible="false" />
<asp:Table runat="server" ID="table_Uc_AddModule" Visible="false">
<asp:TableRow runat="server">
<asp:TableCell runat="server" >
<asp:PlaceHolder ID="ph_Uc_AddModule" runat="server">
</asp:PlaceHolder>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow1" runat="server">
<asp:TableCell runat="server" CssClass="td_Tb_AddModule" HorizontalAlign="Center">
<asp:Button ID="btn_Insert" runat="server" OnClick="Uc_AddModule_ItemInsert" Text="" CssClass="btn_Add" />
<asp:Button ID="btn_Cancel" runat="server" OnClick="Uc_AddModule_Clear" Text="" CssClass="btn_Clear" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Panel>
i'm using below method in my insert function at the code behind to access the data inserted at the textbox:
for (int i = 1; i <= nonPkCounter; i++)
{
TextBox textBox = (ph_Uc_AddModule.FindControl("tb" + i + "_AddModule")) as TextBox;
}
i have tried pn_Uc_TModule.FindControl("tb" + i + "_AddModule") and also This.ph_Uc_AddModule.FindControl("tb" + i + "_AddModule") but still con not get the texbox data to insert it to database.
could you please guide me how to get it done.
appreciate your consideration.
You should call CreateAddDynamicTable on your Init event always. That will make the viewstate make sense and asp.net will load all the values to the controls. Then you can add the textboxes to a collection and access them without using FindControl, just the references, in your Page_Load event.

Categories