I have a dynamically created asp table, which have 4 columns. First column is text, second textbox, third and fourth are text. I need to iterate through the table and get the value from textbox. But I am getting this exception when I am trying to get the textbox value : Specified argument was out of the range of valid values. I set the cell index as 1 as the textbox is located in second column. How can I get the text from textbox?
foreach (TableRow row in this.reading.Rows)
{
var textbox = (TextBox)row.Cells[1].Controls[1];
string id = row.Cells[3].Text;
if (textbox.Text != "")
{
double f = Convert.ToDouble(textbox.Text);
DBConn.update(f, id);
}
else
{
}
}
As dime2lo mentions its hard to find the error without debugging / providing more info.
Try instead of assigning textbox to the the 2nd control in the table row assign it to controls and remove your angle brackets.
var controls = row.Cells[1].Controls;
Then iterate through the controls
foreach (Control c Controls)
{
//Debug in here.
}
This will at least help you see where it's going wrong.
Related
I have the following code in a button click method that goes through the rows of a GridView. ServiceFormQuestionTypeIDHF is a HiddenField.
The first time through the foreach statement the value of sfqtIdINT is 10 and the value of sfqtIdSTR is "10" yet the if statement is true. Now the value I am expecting for the HiddenField.ToInt() is 1.
I can confirm that the rest of the foreach statement and the rest of the if statements display the wrong value in sfqtIdSTR and sfqtIdINT but the behavior of the if statement is the value I am expecting from that row in the GridView. In other words the HiddenField has the right value but displays the wrong value.
I can see no reason for this. Can anyone provide a reason for this?
foreach (TableRow tr in FormGV.Rows)
{
HiddenField ServiceFormQuestionTypeIDHF = (HiddenField) tr.FindControl("ServiceFormQuestionTypeIDHF");
int sfqtIdINT = ServiceFormQuestionTypeIDHF.Value.ToInt();
string sfqtIdSTR = ServiceFormQuestionTypeIDHF.Value;
if ((ServiceFormQuestionTypeIDHF.Value.ToInt() == 1 )||
(ServiceFormQuestionTypeIDHF.Value.ToInt() == 2))
{ .......
.......
}
Try using GridViewRow instead of TableRow in foreach.
Great website - very helpful in my C# Class.
I am trying to write a method in C# that will Check fields for null entry and change field background to LightYellow?
The form is a display form that views records in a SQL database.
Here is what I tried - but the variable for the field names isn't translating to the field name.
Advice?
// YellowBack Method fills background of key fields that are missing data or are NULL
private void YellowBack()
{
//Bool fieldContents = true;
string fieldVariable;
string[] fieldName = { "activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox", "review_AdultTextBox",
"phoneTextBox", "addressTextBox", "cityTextBox", "websiteTextBox", "weblink_TextTextBox",
"hoursTextBox", "admissionTextBox" };
int count = 0;
//Check each field name
for (int index = 0; index < fieldName.Length; index++)
{
fieldVariable == fieldName.Text;
if (fieldVariable.Trim = "")
{
fieldVariable.BackColor = LightYellow;
}
else
{
fieldVariable.BackColor = Window;
}
}
}
You are not using the index . . . . you should be using something like:
fieldVariable = fieldName[i].Text;
I also think that you won't be able to set the property BackColor on fieldVariable as it is a string. You should probably be using the object grid or text control that your database binds to and setting the color properties of that . . . but I'm not sure there's enough information here to go on.
I think the problem is that you're looping through a list of strings and trying to make the string into a TextBox control. Instead, you should probably loop through all the controls on the form, and for each one that is a TextBox, see if it's name matches a name in your list. Then you can set the back color of the control based on the Text property.
There are other problems with your code also, like in your if statement you are doing an assignment (=) instead of a comparison (==).
Here's what I would do:
private void HighlightEmptyFields()
{
// Create a list of all the text box names that we want to examine
var textBoxNames = new List<string>
{
"activity_TitleTextBox", "act_Title2TextBox", "kid_NotesTextBox",
"review_AdultTextBox", "phoneTextBox", "addressTextBox", "cityTextBox",
"websiteTextBox", "weblink_TextTextBox", "hoursTextBox", "admissionTextBox"
};
// Loop through every control on the form
foreach (Control formControl in this.Controls)
{
// Find the groupbox control by name
if (formControl.Name != "groupBox1") continue;
// We found the group box, so loop through every control in it
foreach (Control groupBoxControl in formControl.Controls)
{
// Try to cast the control to a TextBox.
var textBoxControl = groupBoxControl as TextBox;
// If the cast fails, move on to the next one...
if (textBoxControl == null) continue;
// Now we have one a textbox control, so see if the
// textBoxNames array contains the name of this text box.
if (textBoxNames.Contains(textBoxControl.Name,
StringComparer.OrdinalIgnoreCase))
{
// We found a match, so set the backcolor based on Text property
if (textBoxControl.Text.Trim() == "")
{
textBoxControl.BackColor = Color.LightYellow;
}
else
{
textBoxControl.BackColor = Color.White;
}
}
}
// Since we found the control we were looking for, we can stop looking
break;
}
}
I'm trying to get the current selected value from a DataGridView
MessageBox.Show(""+dataGridView1.SelectedCells.ToString()+"")
but it never shows the selected value.
It shows
System.Windows.Forms.DataGridViewSelectedCellCollection
you should do it this way
MessageBox.Show(dataGrdiView1.SelectedCells[0].Value.ToString());
try to access Value or Text of a single cell, and not the entire collection
you can also iterate through the entire SelectedCells collection
string text;
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
//MessageBox.Show(cell.Value.ToString());
text +=cell.Value.ToString();
}
MessageBox.Show(text);
If it always a single cell selected you could just use. dataGridView1.SelectedCells[0].tostring. The reason you are getting the class name ia because you are getting back a collection of selected cells as their couls be more than one cell selected at a time.
string message = string.Empty;
foreach (var c in _dataGridView1.SelectedCells)
message += " " + c.Value.ToString();
MessageBox.Show(message);
Working with a GridView in C# (ASP.NET) and I'm trying to iterate over a single row. Normally it wouldn't be too difficult if I could extract the text in each cell:
string text = SecGrpGridView.Rows[0].Cells[i].Text;
However, some of the fields in my row contain Labels and I believe the only way to extract the value is using FindControl() and casting it to a Label:
Label myLabel = (Label)SecGrpGridView.Rows[0].Cells[i].FindControl("Label5");
string text = myLabel.Text;
As you can see, the second example I needed to know the ID of my label so it makes it difficult to iterate over unless I have sequentially named labels. I know that a future need will be to add more columns to my row so I'm looking for a way to iterate over this row without having to name the labels sequentially. (ie 'Label1', 'Label2', 'Label3') Is there a better way to go about this?
You can gather all the Labels in GridView by using the following code
public static List<Label> FindLabelRecursive(Control root)
{
List<Label> labels = new List<Label>();
if (root is Label)
{
labels.Add(root as Label);
return labels;
}
foreach(Control c in root.Controls)
{
if (c is Label)
{
labels.Add(c);
}
else
{
List<Label> childLabels = FindLabelRecursive(c);
labels.AddRange(childLabels);
}
}
return labels;
}
Then do you processing based on the labels returned.
I would like to know how can I get a column name from a gridview? by its number not by name.
like : Name|Age|Birthday: ( so name=0 , age=1 etc...)
thanks.
You can get it like this :
gv.HeaderRow.Cells[i].Text
Or like this :
gv.Rows[0].Cells[i].Text
Rows[0] should be your header row.
//// Header column names
int gridViewCellCount = yourGridView.Rows[0].Cells.Count;
// string array to hold grid view column names.
string[] columnNames = new string[gridViewCellCount];
for (int i = 0; i < gridViewCellCount; i++)
{
columnNames[i] = ((System.Web.UI.WebControls.DataControlFieldCell)(yourGridView.Rows[0].Cells[i])).ContainingField.HeaderText;
}
simply
GridView1.Rows[0].Cells[0].Text;
try this if you want to all the cells value from each of the rows
foreach (GridViewRow r in GridView1.Rows)
{
string s = r.Cells[0].Text;
string y = r.Cells[1].Text;
}
update:
try this
foreach (TableCell Tc in GridView1.HeaderRow.Cells)
{
//if you are not getting value than find childcontrol of TabelCell.
string sssb = Tc.Text;
foreach (Control ctl in Tc.Controls)
{
//Child controls
Label lb = ctl as Label;
string s = lb.Text;
}
}
Revisiting this old question.... it's possible to get the field names of the data bound to a GridView with this kind of code. This makes a dictionary of colnum and field name.
private static IDictionary<int, string> GetGridViewFieldNames(object grid)
{
var names = new Dictionary<int, string>();
var view = grid as GridView;
if (view != null) {
for (var i = 0; i < view.Columns.Count; i++) {
var field = view.Columns[i] as BoundField;
if (field != null) {
names.Add(i, field.DataField);
}
}
}
return names;
}
This is not the answer to the question. It is only the answer if you never change the header text in the gridview. The asker of the question wanted to get the database field name by index.
I've seen a number of "answers" which only provide the text in the selected row of a gridview, or the header text which both do not answer the question that was asked...
You may ask why? If you were going to do audits of updates in a system and wanted to compare old values and new values and only update if they change and want to indicate which field was updated how do you show the database table field name at the index of the loop.
For instance:
Protected Sub gv_RowUpdating(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs)
Dim intValCount As Integer = Integer.Parse(e.NewValues.Count)
If intValCount > 0 Then
Dim i As Integer = 0
For i = 0 To intValCount - 1
If Not e.OldValues(i).Equals(e.NewValues(i)) Then
' values have changed, audit the change
Sys.Audits.General(intID, "the_database_table", <the table field by index(i)>, e.OldValues(i).ToString, e.NewValues(i).ToString)
End If
i += 1
Next
End If
End Sub
So the questions is how do you get the database table field name by index via code behind? I too have been searching for this and all the "answers" that I've seen are not the answers I think some of us are really looking for. All the mentioned methods I've seen here are not bullet proof references to a database tables field name.
Its easy: Here i read the gridview header text for each header cell and add them as new columns to a data table.
DataTable dt = new DataTable();
foreach(DataControlFieldHeaderCell column in yourGridview.HeaderRow.Cells)
{
dt.Columns.Add(column.Text.Trim().Replace(" ", ""));
}
//Make sure you do all this after yourGridview.DataBind();
//If you do not want to bind data first simply bind an empty list like so:
/* yourGridview.DataSource = new List<string>();
yourGridview.DataBind(); */