I have controls that are named in numeric sequence.
I'd like to assign values those controls using loop.
The code below is the way i'm currently using.
txtSalesInvoiceForm_Qty1.Text = (salesInvoice.ItemQty1 == 0) ? string.Empty : salesInvoice.ItemQty1.ToString();
txtSalesInvoiceForm_Qty2.Text = (salesInvoice.ItemQty2 == 0) ? string.Empty : salesInvoice.ItemQty2.ToString();
txtSalesInvoiceForm_Qty3.Text = (salesInvoice.ItemQty3 == 0) ? string.Empty : salesInvoice.ItemQty3.ToString();
txtSalesInvoiceForm_Qty4.Text = (salesInvoice.ItemQty4 == 0) ? string.Empty : salesInvoice.ItemQty4.ToString();
txtSalesInvoiceForm_Qty5.Text = (salesInvoice.ItemQty5 == 0) ? string.Empty : salesInvoice.ItemQty5.ToString();
txtSalesInvoiceForm_Unit1.Text = salesInvoice.Unit1;
txtSalesInvoiceForm_Unit2.Text = salesInvoice.Unit2;
txtSalesInvoiceForm_Unit3.Text = salesInvoice.Unit3;
txtSalesInvoiceForm_Unit4.Text = salesInvoice.Unit4;
txtSalesInvoiceForm_Unit5.Text = salesInvoice.Unit5;
txtSalesInvoiceForm_Particulars1.Text = salesInvoice.Particulars1;
txtSalesInvoiceForm_Particulars2.Text = salesInvoice.Particulars2;
txtSalesInvoiceForm_Particulars3.Text = salesInvoice.Particulars3;
txtSalesInvoiceForm_Particulars4.Text = salesInvoice.Particulars4;
txtSalesInvoiceForm_Particulars5.Text = salesInvoice.Particulars5;
Is there any way something like this?
int index = 1;
foreach (SalesInvoiceItem item in salesInvoice.SalesInvoiceItems)
{
(txtSalesInvoiceForm_Qty + index.ToString()).Text = Value;
indexer++
}
Control parent = this.pnlParent; // this must be the immediate parent control
int index = 1;
foreach (SalesInvoiceItem item in salesInvoice.SalesInvoiceItems)
{
TextBox tb = parent.FindControl( "txtSalesInvoiceForm_Qty" + index++ ) as TextBox;
tb.Text = Value;
}
The key is FindControl(), which searches the immediate children of a parent. Personally I think this is sloppy code in most cases.
Use an array rather than so many named variables and just index into the array.
Related
Im using the following code to split up a string and store it:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
The problem is i am getting
Index was outside the bounds of the array.
When proxyAdrs[2] is not there.
Sometimes proxyAdrs[2] will be there sometimes not.
How can i solve this?
Just check the length of the array returned in your if statement
if( proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
The reason you are getting the exception is that the split is returning array of size less than the index you are accessing with. If you are accessing the array element 2 then there must be atleast 3 elements in the array as array index starts with 0
You can check the length of array before accessing its element by index.
Change
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
To
if(proxyAdrs.Length > 2 )
{
item.Username = proxyAdrs[2];
}
Try this:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs.Length > 3 && proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
Check the length of proxyAdrs before you attempt to subscript a potentially non-existent item.
if ( proxyAdrs.Length > 1 ) {
item.Username = proxyAdrs[2];
}
It is that your i which might be lower than the 2 you are trying to set in as index :)
if i >= 2 then you can do all of the follwing:----
if(proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
if (proxyAdrs[3] != null)
{
item.Password = proxyAdrs[3];
}
}
else I suggest you get out :D
But again, checking proxyAdrs.Lenght would be the best.
There are two options that may help you, depending of whether or not you form incoming data (variable linesProxy):
If you do form incoming data: Always include all parts of the string. In your case, always ensure you have 4 (assuming proxyAdrs[3] is the last) parts by adding additional : between 1st and 3rd values if no value for 2nd is provided. Thus after .Split() operation (ensure you don't activate RemoveEmptyStrings option ) your proxyAdrs[2] will be null and your sample will be fine.
Otherwise: if proxyAdrs[2] is the only part the can be empty following snippet can prevent crashing:
string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);
if(proxyAdrs.Length > 3)
{
if(proxyAdrs[2] != null)
item.Username = proxyAdrs[2];
if (proxyAdrs[3] != null)
item.Password = proxyAdrs[3];
}
else
{
if(proxyAdrs[2] != null)
item.Password = proxyAdrs[2];
}
try
{
objCommonDD = new CommonDropDownBLL();
objCommonDDEntity = new CommonDropdownEntity();
//string strState=contextKey.ToString();
string[] contextKeySplit = contextKey.Split('^');
string strState = contextKeySplit[0].ToString();
string strPin = contextKeySplit[1].ToString();
objCommonDDEntity.TableName = "PCOM_PINCODES";
objCommonDDEntity.DeleteField = "";
objCommonDDEntity.TextField = "RTRIM(PIN_CITY_NAME) AS PC_DESC";
objCommonDDEntity.ValueField = "DISTINCT PIN_CITY_CODE AS PC_CODE";
objCommonDDEntity.StrCondition = " AND PIN_COUNTRY_CODE='IND' AND UPPER(PIN_CITY_NAME) LIKE UPPER('" + prefixText + "%') AND PIN_STATE_NAME='" + strState + "' AND PIN_CODE='" + strPin + "' ORDER BY PC_DESC";
DataTable dtCity = new DataTable();
dtCity = objCommonDD.GetData(objCommonDDEntity);
string[] items = new string[dtCity.Rows.Count];
int i = 0;
for (i = 0; i < dtCity.Rows.Count; i++)
{
items.SetValue(dtCity.Rows[i]["PC_DESC"].ToString(), i);
}
return items;
}
I have managed to pull out the FirstorDefault() in the Query, however, some of these address types in the database actually have more than 1 address: therefore, I am trying to build an array of every address regarding each one.
The current code:
int counter = 0;
string queryID = "";
List<string> busAddr = new List<string>();
while (counter != busIDs.Count)
{
queryID = busIDs[counter];
var gathered = (from c in db.tblbus_address where c.BusinessID == queryID && c.AddressTypeID == addrnum select c).ToArray();
int gath = 0;
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
var address = gathered[gath] as tblbus_address;
string test = "";
while (gath != address.Address1.Length)
{
var all = address.Address1;
test += address.Address1.ToString() + ",";
}
busAddr.Add(test);
}
else
{
busAddr.Add("No address for this type exists...");
}
counter++;
gath++;
}
I am receiving an error:
Index was outside the bounds of the array.
at this line:
if ((gathered[gath] as tblbus_address) != null && !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
Can anyone point me in the right direction? I know this structure is the issue but I cannot think how to approach the situation.
You are trying to get the element gathered[gath] when there are no items in gathered. Adding a check for null and Any will help you
if(gathered!=null && gathered.Any()
&& (gathered[gath] as tblbus_address) != null
&& !string.IsNullOrEmpty((gathered[gath] as tblbus_address).Address1))
{
...
...
}
Whats the best way for me to change the ID's of the check boxes, like as in using a loop, the problem I'm having is with the current control ID CheckBox1.ID, i cant seem to change the 1 to be used as a variable
CheckBox1.ID = "chckbx_1";
CheckBox2.ID = "chckbx_2";
CheckBox3.ID = "chckbx_3";
CheckBox4.ID = "chckbx_4";
CheckBox5.ID = "chckbx_5";
CheckBox6.ID = "chckbx_6";
Is there any way where i can implement this logic?, and please note, I'm using web forms
Try something like this:
for (int i = 1; i < some_number; i++)
{
Control myControl = FindControl("CheckBox" + i.ToString());
if(myControl != null && myControl.GetType() == typeof(CheckBox))
{
((CheckBox)myControl).ID = "chckbx_" + i.ToString();
((CheckBox)myControl).CssClass = "newClass";
}
}
I will disable the CheckBoxList once a user selects 5 values.
I want to take the 5 selected items out of the CheckBoxList and assign them to 5 different labels.
So far I have this:
string test = "";
string test2 = "";
test += CheckBoxList.SelectedValue[0];
test2 += CheckBoxList.SelectedValue[1];
Label1.Text = test;
Label2.Text = test2;
All that does is get the first character and assign the same value to both labels. How would I iterate through and take each selected value and assign them to the each label?
var labels = new List<string>();
int count = 0;
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
labels.Add(item.Value);
}
string mylabel1 = labels.Count > 0 ? labels[0] : string.Empty;
string mylabel2 = labels.Count > 1 ? labels[1] : string.Empty;
string mylabel3 = labels.Count > 2 ? labels[2] : string.Empty;
string mylabel4 = labels.Count > 3 ? labels[3] : string.Empty;
string mylabel5 = labels.Count > 4 ? labels[4] : string.Empty;
Here's a generic code, suitable for 5 or 50 items/labels:
var selected = CheckBoxList.Items.Cast<ListItem>().Where(it => it.Selected)
for (i=0; i < selected.Count(); i++)
{
lb = FindControl("Label" + i);
if(lb != null)
((Label)lb).Text = selected.ElementAt(i).Value;
}
Update
Since you stated you don't have LINQ, you can go like this:
int i = 0;
foreach (var item in CheckBoxList.Items)
{
if (item.Selected)
{
lb = FindControl("Label" + i);
if(lb != null)
((Label)lb).Text = item.Value;
i++;
}
}
Update 2
Keep in mind that both solutions assume that your labels start at Label0. Adjust accordingly. Also, code was adjusted to check if the Label was found.
OK, I have a code (see below):
void M1()
{
for (int i = 1; i < 10; i++)
{
Control[] carr = this.Controls.Find("Number" +
(i - 1).ToString() +
"CheckBox", true);
if ((carr != null) && (carr.Length > 0))
{
CheckBox enableCB = carr[0] as CheckBox;
enableCB.Checked = i % 2 == 0 ? true : false; // or any other value
}
}
}
I don't like iteration with using Controls.Find method. Can I replace it with something easier ?
PS: all the NumberXCheckBox (X>=0 and X<=8) presented on the form.
LINQ enabled, .net 3.5, Visual studio 2008.
Instead of searching by name, can you wrap your CheckBox controls in a container that means you can just iterate through the controls in the container?
I would encourage you to introduce a field in your type to keep references to your checkboxes (an array, a list, a dictionary -- you choose.) This way you'll no longer need to use this non-typed and somewhat ugly find-control-by-key-method.
Anyway, if you're still in .NET 2.0 and prefer to use the Find method, you could simplify a little bit your loop:
for (var i = 0; i <= 8; i++)
{
var controls = Controls.Find("Number" + i + "CheckBox", true);
if (controls.Length > 0)
{
var checkBox = controls[0] as CheckBox;
if (checkBox != null)
checkBox.Checked = i%2 == 0;
}
}
The latest non-nullity test on checkbox can probably be omitted.
If you are using 3.5 or otherwise have LINQ available you could do the following
for ( int i = 0; i < 9; i++) {
var control = this.Controls
.Find(String.Format("Number{0}Checkbox", i))
.Cast<CheckBox>()
.FirstOrDefault();
if ( control != null ) {
control.Checked = (i % 2) != 0;
}
}
More linq-y
for (int i = 0; i < 10; i++) {
var c = (from CheckBox c in this.Controls.Find(String.Format(CultureInfo.InvariantCulture, "Number{0}CheckBox", i-1), true)
select c).FirstOrDefault();
if (c != null) {
c.Checked = i % 2 == 0 ? true : false;
}
}
Here's one without linq, but cleaned up the code a little bit.
for (int i = 1; i < 10; i++)
{
Control[] carr = this.Controls.Find("Number" + (i - 1) + "CheckBox", true);
if (carr.Length <= 0) continue;
CheckBox enableCB = carr[0] as CheckBox;
enableCB.Checked = (i % 2) == 0;
}
[Edit: added the Find(..) code to show why you don't have to check for null]
Here's the frameworks internal code for the Find function. I've added a couple of comments in it
public Control[] Find(string key, bool searchAllChildren)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key", SR.GetString("FindKeyMayNotBeEmptyOrNull"));
}
// Will always return an ArrayList with zero or more elements
ArrayList list = this.FindInternal(key, searchAllChildren, this, new ArrayList());
// Will always return an Array of zero or more elements
Control[] array = new Control[list.Count];
list.CopyTo(array, 0);
return array;
}