Getting values from templatefields gridview - C# - c#

I am using a gridview to display a table queried from a database...
In this gridview I also added a buttonfield, and 3 template fields...
When i press the buttonfield the data from the database is acquired, but the
manual data inserted from the template fields are not.. It seems that null values are acquired.
From the xml file i am firing the following event:
OnRowCommand="GridView1_SelectedIndexChanged1"
and have the following method to catch that event:
protected void GridView1_SelectedIndexChanged1(object sender, GridViewCommandEventArgs e)
{
int x = Convert.ToInt32(e.CommandArgument);
GridView1.SelectRow(x);
GridViewRow row = GridView1.Rows[x];
Response.Write(row.Cells[0].Text + "\t");
Response.Write(row.Cells[1].Text + "\t");
Response.Write(row.Cells[2].Text + "\t");
Response.Write(row.Cells[3].Text + "\t");
Response.Write(row.Cells[4].Text + "\t");
Response.Write(row.Cells[5].Text + "\t");
Response.Write(row.Cells[6].Text + "\t");
Response.Write(row.Cells[7].Text + "\t");
Response.Write(row.Cells[8].Text + "\t");
}
Any ideas on how i can get the values from that template field? do i need to catch another event rather than GridViewCommandEventArgs? If so what event should i throw from the xml part?
Thanks,

You can find the control u added on to the row and then use the text property to get the value of it.
Something similar to row.FindControl(<urIdgoeshere>)\\cast it to textBoxand then use .Text to get the value of it .
GridViewRow row = GridView1.Rows[x];
Response.Write((TextBox)row.FindControl('txtbox1')).Text;

I am fighting with the same, I used to use the Cells[] code with asp BoundField.
Now i had to switch to template fields as I need buttons etc in the footer.
I am pulling my hair out, I use the same code as suggested by Ashley, and I get System.NullReferenceException: Object reference not set to an instance of an object.
I am doing this within the row command event.
Been this way since 3 days :(
Edit:
Quick Solution to my issue: I've created the ID given Field on the footer, and I had not given and ID to my ItemTemplate, i.e the only thing I had in there was <%# Eval("Description")%>
There looks like to be NO WAY to select this data without giving it some kind of ID in code behind. I was stupid and had not noticed this simple fact later on.

Related

In a DataGridView, how do you get the pre-edited cell values back in that row?

I created a DataRow and set it equal to the row of the DataSet that is the equivalent current row of the grid. I want to isolate the original pre-edited values so I can revert back to these values in the grid if the user cancels the edits for that row. But the grid seems to be bound to the DataSet so that it is not isolating the original pre-edited cell values. I coded so it only creates the DataRow once in the CellBeginEdit event. But each time I edit a cell, the DataRow is changing and reflecting the new edited values. I tried using a DataGridViewRow but it also changed automatically with each cell edit rather than being an independent snapshot of the row at the time it was created. Here is my code:
private void gridDB_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
string test;
//DataGridViewRow currRow= new DataGridViewRow(); This kept updating with each edit
//rowSet is public bool and currRow is public DataRow
if (rowSet != true)
{
currRow = dSet.Tables[0].Rows[gridDB.CurrentRow.Index];
rowSet = true;
}
test = "In CellBeginEdit " + currRow[0].ToString() + " " +
currRow[1].ToString() + " " +
currRow[2].ToString() + " " +
currRow[3].ToString() + " " +
currRow[4].ToString();
MessageBox.Show(test);
}
Each time it came to this test string, it was showing each new edited cell edit. This told me that currRow is not a static snapshot of the DataSet row at the time it was created.
Please tell me why this does not work and advise me of the best way to be accomplish this.
Thank you!
Valhalla

Checking a column value when updating a gridview asp.net

I'm trying to do some error handling on a column to see if it's not equal to a certain word. I'm wondering though do i do this on the RowUpdating event or the RowUpdated event. I've been trying to do this in the rowupdating event and haven't had any luck so far. Here's the code.
TableCell cell = GridView1.Rows[e.RowIndex].Cells[3];
if(cell.Text == "hello")
{
e.Cancel = true;
}
lblError.Text = "hello" + cell.Text;
I assume the 3 after inside the brackets after .Cells is the column index that I want. If i use .Cells[1] it will show the primary key no in the label, but if I try 2 or 3 nothing seems to be getting placed inside the cell variable.
My table has four columns, ID, Name, Price, and CategoryID. Any help is appreciated.
If you are trying to get the input box values, you will have to find the control like:
GridViewRow row = GridView1.Rows[e.RowIndex];
string price = ((TextBox)(row.Cells[3].Controls[0])).Text;
You can also check against the e.NewValues.
And fyi: You will have to set the e.Cancel=true, if you want to cancel the event upon meeting certain condition(s).
Check RowUpdatingEvent ref.

How to select row in Telerik RadGrid?

When user select a row in Telerik Rad Grid, i want to take fields in this row. how to do this?
It's a little tricky, but easy after you've done it once.
Step 1.
Go to the Radgrid itself and edit the field DataKeyNames="" (under MasterTableView) and add the datafield you are pulling:
<MasterTableView ... DataKeyNames="ColumnNameFromSqlGoesHere">
Step 2.
Decide how you are going to grab the values, on Row Change (SelectedIndexChanged) or on a buttong press with a command attached to it (ItemCommand).
If row change, per your question:
protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
{
var z = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["ColumnNameFromSqlGoesHere"];
}
This will assign the variable "z" to the value of the column you have chosen (ColumnNameFromSqlGoesHere) at that given row.
If you wish to select multiple variables every time you change row you need to add all the values you wish to select under the DataKeyNames=" ". (Seperated by commas). You would then fetch each value via the code seen in the SelectedIndexChanged method:
var a = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["SecondColumnGoesHere"];
var b = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["ThirdColumnGoesHere"];
Etc... You get the idea.
This should get you going. It is a solution straight from Telerik: Retrieving primary key values for selected items
Try this. This may help you.
STEP 1:Add one radiobutton column in the radgrid
STEP 1: Get the primary key of selected row in the radgrid.
int primaryKey =0;
RadioButton radioButton;
for (int i = 0; i < RadGrid1.Items.Count; i++)
{
radioButton = RadGrid1.Items[i].FindControl("rdSelect") as RadioButton;
If (radioButton.Checked)
{
primaryKey = RadGrid1.MasterTableView.Items[e.Item.ItemIndex]["ID"].Text;
}
}
Line in the if condition will be used to get the fields from the selected row just by changing the fields datakey name i.e. changing "ID" to other field
Read this article for more details...
http://codedotnets.blogspot.in/2012/01/get-primary-key-selected-radiobutton.html

Error: Deleted row information cannot be accessed through the row

To whom this may concern, I have searched a considerable amount of time, to work a way out of this error
"Deleted row information cannot be accessed through the row"
I understand that once a row has been deleted from a datatable that it cannot be accessed in a typical fashion and this is why I am getting this error. The big issue is that I am not sure what to do to get my desired result, which I will outline below.
Basically when a row in "dg1" is deleted the row beneath it takes the place of the deleted row (obviously) and thus inherits the deleted rows index. The purpose of this method is to replace and reset the rows index (via grabbing it from the corresponding value in the dataset) that took the deleted rows place and as such the index value.
Right now I am just using a label (lblText) to try and get a response from the process, but it crashes when the last nested if statement trys to compare values.
Here is the code:
void dg1_Click(object sender, EventArgs e)
{
rowIndex = dg1.CurrentRow.Index; //gets the current rows
string value = Convert.ToString(dg1.Rows[rowIndex].Cells[0].Value);
if (ds.Tables[0].Rows[rowIndex].RowState.ToString() == "Deleted")
{
for (int i = 0; i < dg1.Rows.Count; i++)
{
if (Convert.ToString(ds.Tables[0].Rows[i][0].ToString()) == value)
// ^ **where the error is occurring**
{
lblTest.Text = "Aha!";
//when working, will place index of compared dataset value into rowState, which is displaying the current index of the row I am focussed on in 'dg1'
}
}
}
Thanks ahead of time for the help, I really did search, and if it is easy to figure out through a simple google search then allow myself to repeatably hate on me, because I DID try.
gc
You can also use the DataSet's AcceptChanges() method to apply the deletes fully.
ds.Tables[0].Rows[0].Delete();
ds.AcceptChanges();
The current value for the data column in the inner if statement will not be available for deleted rows. To retrieve a value for deleted rows, specify that you want the original value. This should fix your error:
if (Convert.ToString(ds.Tables[0].Rows[i][0, DataRowVersion.Original].ToString()) == value)
In your "crashing if", you can check if the row is deleted before accessing it's values :
if (ds.Tables[0].Rows[i].RowState != DataRowState.Deleted &&
Convert.ToString(ds.Tables[0].Rows[i][0].ToString()) == value)
{
// blaaaaa
}
Also, I'm not sure why you ToString() the RowState instead of comparing it to DataRowState.Deleted.
after deleting the row , rebind your grid with the datatable , no need to manually resetting index , datatable handels it.
so you onl;y need to rebind grid's datasource.

Using empty row as default in a ComboBox with Style "DropDownList"?

I am trying to write a method, that takes a ComboBox, a DataTable and a TextBox as arguments. The purpose of it is to filter the members displayed in the ComboBox according to the TextBox.Text. The DataTable contains the entire list of possible entries that will then be filtered. For filtering, I create a DataView of the DataTable, add a RowFilter and then bind this View to the ComboBox as DataSource.
To prevent the user from typing into the ComboBox, I choose the DropDownStyle DropDownList. That’s working fine so far, except that the user should also be able to choose nothing / empty line. In fact, this should be the default member to be displayed (to prevent choosing a wrong member by accident, if the user clicks through the dialog too fast).
I tried to solve this problem by adding a new Row to the view. While this works for some cases, the main issue here is that any DataTable can be passed to the method. If the DataTable contains columns that cannot be null and don’t contain a default value, I suppose I will raise an error by adding an empty row.
A possibility would be to create a view that contains only the column that is defined as DisplayMember, and the one that is defined as ValueMember. Alas, this can’t be done with a view in C#. I would like to avoid creating a true copy of the DataTable at all cost, since who knows how big it will get with time.
Do you have any suggestions how to get around this problem?
Instead of a view, could I create an object containing two members and assign the DisplayMember and the ValueMember to these members? Would the members be passed as reference (what I hope) or would true copied be created (in which case it would not be a solution)?
Thank you very much for your help!
Best regards
public static void ComboFilter(ComboBox cb, DataTable dtSource, TextBox filterTextBox)
{
cb.DropDownStyle = ComboBoxStyle.DropDownList;
string displayMember = cb.DisplayMember;
DataView filterView = new DataView(dtSource);
filterView.AddNew();
filterView.RowFilter = displayMember + " LIKE '%" + filterTextBox.Text + "%'";
cb.DataSource = filterView;
}
Ok, by chance, I stumbled over a working solution: Any changes to a DataView - such as adding a new row - are supposed to be completed using .EndEdit. If you don't do that, you'll be confronted with side effects, such as the added row not being sorted properly. BUT: by not adding .EndEdit, you'll also get an advantage: C# won't check, if any of the columns in the underlying DataTable (dtSource) does not allow null!
So, as a solution, I added .EndEdit to a try-Block. If the DataTable allows null for every column, it will work and the empty line will appear on top of the combobox. If it doesn't allow null, EndEdit won't be executed, the empty line will still be added, at the bottom of the ComboBox, however.
Please note that if you have set autoincrement in dtSource, the empty line will also return a SelectedValue (most likely -1). This needs to be considered when using this method!
Cheers!
public static void ComboFilter(ComboBox cb, DataTable dtSource, TextBox filterTextBox)
{
cb.DropDownStyle = ComboBoxStyle.DropDownList;
string displayMember = cb.DisplayMember;
DataView filterView = new DataView(dtSource);
DataRowView newRow = filterView.AddNew();
newRow[displayMember] = "";
try { newRow.EndEdit(); } // fails, if a column in dtSource does not allow null
catch (Exception) { } // works, but the empty line will appear at the end
filterView.RowFilter = displayMember + " LIKE '%" + filterTextBox.Text + "%'";
filterView.Sort = displayMember;
cb.DataSource = filterView;
}

Categories

Resources