Getting values from Dynamic controls in Grid view - asp.net

I am generating a Gridview with Custom controls (Text boxes) as per the user input during the run time. when i try to access the data in those text boxes, its not happening
I had triggered this operations with the Button and the code is as follows:
for (int rowCount = 0; rowCount <= gvCapacity.Rows.Count; rowCount++)
{
for (int i = 1; i < gvCapacity.Columns.Count; i++)
{
if (i > rowCount)
{
if (!(gvCapacity.Columns[i].HeaderText == "Route" && gvCapacity.Columns[i].HeaderText == "Location" && gvCapacity.Columns[i].HeaderText == "RouteLocationID"))
{
TextBox txtBox = gvCapacity.Rows[rowCount].Cells[i].FindControl("txt" + gvCapacity.Columns[i].HeaderText) as TextBox;
}
}
}
It returns the Null value when i try to access the textbox data.
Can anyone help me out on this.
Regards
Geeta

If you mean the texbox variable "txtbox" is always null it looks like that would be because you're asking that the headertext be two different things in your if conditional:
.. && gvCapacity.Columns[i].HeaderText == "Location" && gvCapacity.Columns[i].HeaderText == "RouteLocationID
which it never will be... one assumes. i.e. FindControl is never evaluated. Maybe one of those && should be an ||?

Related

Getting error When dt.value length is < 4

I have this code which works fine as long as as dt.Value is different to "int".
This is the line which errors:
(dt.Value.ToLower().Substring(0, 4).Equals("date"))
It works fine if dt.Value is varchar or datetime.
I provided my suggested solution at the end of this post.
// Edit
if (e.CommandName == "Edit")
{
// Get the item
RepeaterItem Item = ((RepeaterItem)((Button)e.CommandSource).NamingContainer);
// Get buttons and repeater
Button savebtn = (Button)(Item.FindControl("btnSave"));
Button editbtn = (Button)(Item.FindControl("btnEdit"));
Repeater rFields = (Repeater)(Item.FindControl("repFields"));
// Enable my fields
foreach (RepeaterItem RI in rFields.Items)
{
// Get data type
HiddenField dt = (HiddenField)(RI.FindControl("hdnDBDataType"));
// Set controls
if (RI.FindControl("chkSetting").Visible) ((CheckBox)RI.FindControl("chkSetting")).Enabled = true;
if (RI.FindControl("ddlSetting").Visible) ((DropDownList)RI.FindControl("ddlSetting")).Enabled = true;
if (RI.FindControl("txtSetting").Visible)
{
((TextBox)RI.FindControl("txtSetting")).Enabled = true;
// Check my data type
if (dt.Value.ToLower().Substring(0, 4).Equals("date")) ((CalendarExtender)RI.FindControl("extDateTime")).Enabled = true;
}
}
}
Is this a good fix ? TIA
if(dt.Value != "int" && dt.Value.ToLower().Substring(0, 4).Equals("date"))
Substring will throw an error if the second parameter is higher than the lenght of the string. What you need to do is check the length before doing the substring or use a method like #Igor suggested in the comments.
Your suggestion to check != "int" is not fullproof if let's say somehow the value is any string less than 4 characters.
(dt.Value.Length > 3 && dt.Value.ToLower().Substring(0, 4).Equals("date"))
I will also put #Igor suggestion here because it is also fullproof:
(dt.Value.StartsWith("date", StringComparison.OrdinalIgnoreCase)

How to Search a Database Table using One of Two Fields from ASP:TextBox and asp:dropdownlist

I have one textbox to search based on staff name and dropdownlist to search based on staff type. if staff name is entered repeater should load based on txtbox text, if dropdown selected load data related to that perticular selected value. if both are present like if textbox value is entered and as well as dropdown is selected load repeater based on both the data.
Below is the code snippet of search option.
int stype = int.Parse(ddlStafType.SelectedValue);
if (txtsearchname.Text == "" && ddlStafType.SelectedValue == "0")
{
idLoadData();
}
else
{
using (iSchoolDBEntities db = new iSchoolDBEntities())
{
var details = (from si in db.School_StaffInfo
join st in db.iSchool_StaffType on si.StaffTypeID equals st.StaffTypeID
where ((si.SchoolID == schlid) && (si.isDeleted != true)) && ((si.StaffName.StartsWith(txtsearchname.Text)) && (si.StaffTypeID == stype) && ((si.StaffTypeID == stype) || (si.StaffName.StartsWith(txtsearchname.Text))))
select new
{
si.StaffID,
si.StaffName,
si.EmployeeCode,
st.StaffType,
si.UserName
});
RptallStaff.DataSource = details.ToList();
RptallStaff.DataBind();
}
}

DevExpress ASPxComboBox Items Color Change from Code Behind

I have a ASPxComboBox for which I'm binding data based on 2 conditions.
Now,I need to show Color for items in combobox based on condition.
My Code :
var dataMainBranchUsers = (from xx in VDC.SURVEY_USER_DETAILS
where xx.BRANCH_ID == 1 && (xx.USER_LEVEL == 2 || xx.USER_LEVEL == 5)
select new
{
xx.USER_NAME,
xx.USER_ID,
xx.USER_LEVEL
}).ToList();
DataTable dtMainBranchUsers = LINQToDataTable(dataMainBranchUsers);
for (int i = 0; i < dtMainBranchUsers.Rows.Count; i++)
{
string strlevel = dtMainBranchUsers.Rows[i]["USER_LEVEL"].ToString();
string struser = dtMainBranchUsers.Rows[i]["USER_NAME"].ToString();
if (strlevel == "2")
{
dtMainBranchUsers.Rows[i]["USER_NAME"] = struser + " - Admin";
}
else
{
dtMainBranchUsers.Rows[i]["USER_NAME"] = struser + " - Survey User";
}
}
Cmb_UserName.TextField = "USER_NAME";
Cmb_UserName.ValueField = "USER_ID";
Cmb_UserName.DataSource = dtMainBranchUsers;
Cmb_UserName.DataBind();
Now, I need to differentiate based on USER_LEVEL and show colors.
Is this possible?
From DevExpress
I'm afraid, the ASPxListBox (which is the part of the ASPxComboBox) doesn't allow to set specific color for each item.
I suggest you to use the ASPxDropDownEdit. This control allows to put anything in its DropDownWindowTemplateContainer.
For example, you can put the ASPxGridView and set color for each row using the HtmlRowPrepared event handler.
See here.

Duplicate values in multiple textbox

How to validate whether the text in multiple textboxes are unique from each other.
It looks like that in asp.net but its not a valid syntax
bool hasNoDuplicate = (txtEmergencyName1.Text.Trim() <> txtEmergencyName2.Text.Trim() <> txtEmergencyName3.Text.Trim <> txtEmergencyName4.Text.Trim);
I am looking for an efficient appraoch, kind of lambda expression or inbuilt in asp.net
Since you're asking for lambda, here's a linq approach.
var allTxt = new[] { txtEmergencyName1, txtEmergencyName2, txtEmergencyName3, txtEmergencyName4 };
var allText = allTxt.Select((txt, i) => new { Text = txt.Text.Trim(), Pos = i + 1 }).ToList();
bool hasNoDuplicate = !allText.Any(t => allText.Skip(t.Pos).Any(t2 => t.Text == t2.Text));
Put all relevant TextBoxes in a collection like an array and use Enumerable.Any. By skipping all before the current textbox you avoid checking the TextBoxes twice.
If all relevant TextBoxes are in a container control like a Panel, you could also use Enumerable.OfType to find them:
IEnumerable<TextBox> allTxt = this.EmergencyPanel.Controls.OfType<TextBox>();
Side-note: it's premature optimization anyway to look for the most performant way to validate some controls. This is nothing what you are doing constantly and there are never millions of controls. Instead you should look for the shortest or most readable approach.
You can use and && or or || operator accordingly
bool isDuplicate=(txtEmergencyName1.Text.Trim() == txtEmergencyName2.Text.Trim()
&& txtEmergencyName2.Text.Trim() == txtEmergencyName3.Text.Trim);
it will set true or false in the isDuplicate variable.
Edit 1
bool isDuplicate=(txtEmergencyName1.Text.Trim() == txtEmergencyName2.Text.Trim()
&& txtEmergencyName2.Text.Trim() == txtEmergencyName3.Text.Trim
&& txtEmergencyName1.Text.Trim() == txtEmergencyName3.Text.Trim
);
You could also do something like
var test = new TextBox();
var AlltBox = new List<TextBox>() { new TextBox() };
for(int i=1; i == 5;i++)
AlltBox.Add((TextBox)this.FindName("txtEmergencyName"+i));
bool exist = AlltBox.Any(tb => ((tb.Text == test.Text)&& tb.Name != test.Name));
but i don't know about the performance

Gridview remove items

I have I gridview in which the data source is a List<T>. When I try to remove an item from the gridview in my buttonRemove_Click() function another function which handles the RowDeleting event is invoked where I remove the item from the List<T> as well. The problem is that if I select to remove multiple items from the gridview the index of the gridview and that of my List<T> un-syncs. For example I have 10 items in my gridview and in my List and I try to remove the last two items. Here is how I do it in my buttonRemove_Click function
foreach (GridViewRow row in gridViewItems.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("checkBox");
if (cb != null && cb.Checked)
{
gridViewItems.DeleteRow(row.DataItemIndex);
}
}
Then in the RowDeleting function, I'll first receive the event for the index 8, I removed it. Now when it comes to deleting the last item (index 9), then it'll throw exception because the index is out of range. How do I solve this problem?
I think the problem will be solved if I try removing the rows in reverse order i.e. starting from the highest index. Can anyone tell how can this be done?
GVGLCode1.DataSource = dt;
GVGLCode1.DataBind();
int iCount = GVGLCode1.Rows.Count;
for (int i = 0; i <= iCount; i++)
{
CheckBox cb = (CheckBox)GVGLCode1.rows[i].FindControl("checkBox");
if (cb != null && cb.Checked)
{
GVGLCode1.DeleteRow(i);
}
}
Please try with this.
May be it can help u.

Resources