Here is my code:
private void Button1_Click(object sender, System.EventArgs e)
{
StringBuilder str = new StringBuilder();
foreach(DataGridItem dgi in myDataGrid.Items)
{
TextBox myTextBox = (TextBox)(dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox)(dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList)(dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox)(dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
if(myListBox.SelectedItem.Value != null)
{
str.Append(myListBox.SelectedItem.Text);
}
str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);
}
Probably my eyes but there's no line in bold.
If you debug and check the type of the controls that you're using, are they of the correct type? I know I had some trouble in the past that sometimes I had to take Controls[0] and sometimes Controls[1] to obtain the correct control.
Grz, Kris.
Yeah I tried using Controls[0] but it did not worked and gave me that "Specific cast is not valid" error. The bold line below causes "Object reference not set to an instance of an object" This error is only thrown when I dont select any item in the ListBox.
foreach(DataGridItem dgiin myDataGrid.Items)
{
TextBox myTextBox = (TextBox) (dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox) (dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList) (dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox) (dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
if(myListBox.SelectedItem.Value !=null)
{
str.Append(myListBox.SelectedItem.Text);
}
str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);
}
Okay I got it. I had to get the value from the ListBox into a string variable and than compare the string to null and empty.
The following code works:
foreach(DataGridItem dgi in myDataGrid.Items)
{
TextBox myTextBox = (TextBox)(dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox)(dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList)(dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox)(dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
string a = myListBox.SelectedValue;
//string b = myListBox.SelectedItem.Value;
//string c = myListBox.SelectedItem.Text;
if(a != null && a != "")
{
str.Append(myListBox.SelectedItem.Text);
}
str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);
}
0 comments:
Post a Comment