Validation before inserting into Gridview - asp.net

I am adding data in gridview but not using sql, and my question is i want to validate first if i already inserted the data in the gridview before inserting. searching every data in my gridview before inserting, is it possible?

It is possible, set asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" to this method, so when you click on insert it will execute this method, you can do the check before inserting:
Sample code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string val= textBox1.Text();
\\check if the value already exists in the datasource you are binding to gridivew <br/>
if(! value exists)
\\ do the insert
}

Related

Access data from BoundField DataField

how would I access data from <asp:BoundField DataField="DateStart".
I have an IF statement and I want to see if data is > or < than the data in the DataField.
I used to use rows(0).findControl but that wont work anymore.
If today > item.FindControl("btnSelect") And today < item.FindControl("btnSelect") Then
if its possible
You cannot use FindControl on BoundFields, only with TemplateFields. You need to use the cell's Text property:
Dim text = grid.Rows(index).Cells(index).Text ' the cell-index is the column-index '
You need to parse it to DateTime/Date:
Dim dateStart = Date.Parse(text)
If Date.Today > dateStart.Date ...
But if you use RowDataBound instead you can access the original DataItem. But then i need to know more to show you an example.
In the definition of your GridView, add
<asp:GridView .... DataKeyNames="ItemID" ...>
You also need to use OnRowDataBound, not OnDataBound
<asp:GridView .... DataKeyNames="ItemID" ... OnRowDataBound="GridView_RowDataBound">
Then in your code behind, something like this
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
int ItemId = Int32.Parse(YourGridView.DataKeys[e.Row.RowIndex].Values[0].ToString());
}
}
If you want to find multiple value then set DataKeyNames as
DataKeyNames="ID,Name,COde,Value and so on"

How to edit gridview row inside?

I want to edit row of gridview.For that, I have added showeditbutton = true.I have binded gridview from cs file.Does I need to wite 3 function for that?(For editing I have added 3 function in cs file.).I have taken help from internet.But some point did not understand.
--In aspx
<asp:GridView datakeyname="Id" Id ="Gridview1" onRowEditing="GridView1_RowEditing" RowCancelingEdit=" GridView1_RowCancelingEdit" onRowUpdating ="GridView1_RowUpdating" >
<column>
// hyperlink ,dataTextfield is id
// some checkboxfield.(start from column 6)
</column>
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
//code for Binding grid
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// for fetching value of id and checkboxfield(column 6)
string Id= GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
bool ischeck = (Gridview1.Rows[e.RowIndex].Cells[5].Controls[0] as checkBox).Checked;
// code for updating grid
GridView1.EditIndex = -1;
//Now bind the gridview gain here
}
protected void GridView1_RowCancelingEdit(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = -1;
//Now bind the gridview gain here
}
Does am I going in right direction?What is use of datakey.Does I used properly?Why GridView1.EditIndex = -1 in update and cancel event.Column 6 is checkboxfield.why .Controls[0] is used for accessing that checkboxfield.
If you are using an ObjectDataSource (or SqlDataSource or OleDbDataSource) to databind and use UpdateCommand, DeleteCommand, InsertCommand, then you do not need to explicitly write those three functions for the edit/update operation. You need those functions when you are writing the binding code in code-behind or if you want to do additional work before/after any operation.
RowEditing fires when you click "edit" on the GridView. Here you specify what row to open in editmode by writing GridView1.EditIndex = e.NewEditIndex. You can also write code here to do any work that is required before user is put into editmode. For example, you can check for business rules conditions, and cancel the operation if rules are not met.
RowUpdating fires when you click "save"/"update" on the GridView. This is fired before the actual database operation. If you have an UpdateCommand on the datasource, then you do not need to write database save routine, otherwise you write that here.
DataKeys identify the "key" that identifies the data that is bound. You specify DataKeys while databinding to the GridView. For example, primary key of a database table. This line: string Id= GridView1.DataKeys[e.RowIndex].Values["Id"].ToString()); Here you are picking up the value of the "Id" key (you can have more than one keys) of the current row.
GridView1.EditIndex = -1 in update or cancel specifies that the GridView should no longer be in editmode. If this value is >= 0, then the GridView is put into editmode for that row (index starting from 0). So we set it to -1, to indicate that it should not be in editmode.
Controls[0] is used to pick the first control in that cell (you may have more than one controls). Alternatively, you can also use FindControl.

Assigning a session variable into DetailsView

I have a Session Variable declared and checked that it exists. I would like the DetailsView to display the Session Variable number in the INSERT Textbox in the DetailsView. When the Insert Button is pressed I, require the record in the DetailsView to be despatched to the database, to create an additional record.
From the experimentation I have carried out, it appears to be difficult to penetrate the DetailsView. I imagine that there is a requirement for some "Code Behind" to be included.
You need to use the detailsview Databound event and assign the value to the textbox. e.g.
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
TextBox TextBox1 = DetailsView1.FindControl("TextBox1") as TextBox;
TextBox1.Text = Session["Name"].ToString();
}
}

ASP ListView: How do I access the data that is databound to the rows?

I want to access the data that was databound to my list view when handling list view events such as:
protected void List_ItemDataBound(object sender, ListViewItemEventArgs e)
or
protected void List_ItemCommand(object sender, ListViewCommandEventArgs e)
Inside the events, I can not access the data via somthing like Eval("ID")
Currently we are using a very hacky solution:
string id = e.Item.FindControl("lblID").Text;
Where lblID is a hidden control that is populated with data in the aspx file using:
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
My eyes bleed when I look at this, Is there a better way?
In your event handlers, use the EventArgs object.
e.Item.DataItem
will give you the object you're looking for; you then just need to cast it to the type you need.
This MSDN page has a fuller example.
For the ItemCommand event handler, you may not have this option. In this case, I would use the CommandName and CommandArgument properties of the LinkButton (or whatever you're using). Put your ID as the CommandArgument, you can then pick this up from the event argument object in the event handler.
After a bit of tinkering I found the proper solution:
Data keys need to be added to the list view. Data keys are persistent unlike the data that is databound to a listview. To set the data key just specify the name in the ListView tag:
<asp:ListView ID="MyListview" runat="server" DataKeyNames="ID" ......
Then to access the keys from the event:
protected void MyListView_ItemCommand(object sender, ListViewItemEventArgs e)
{
// Get the item index of the Item
int itemIndex = ((ListViewDataItem)e.Item).DisplayIndex;
// Extract the key and cast it to its data type.
DataKey key = ((ListView)sender).DataKeys[itemIndex];
int myId = (int) key;
// Use ID to delete / modify the item in the SQL database....
}
Just to expand on the ItemDataBoundEvent solution you alluded to, you don't need to go via the ListView's DataKeys to access the data in the ItemDataBoundEvent. Casting e.Item to ListViewDataItem gives you access to the DataItem property which you can then cast to the underlying data type, giving you intellisense access to every underlying data field. Example:-
(ActualDataType)(((ListViewDataItem)e.Item).DataItem)

ASP.NET Formview Item Inserting Event

I'm using the FormView control in ASP.NET for a simple form to insert into a MS SQL DB. I have an event for onItemInserting to set some values behind (such as time stamp, etc) and was curious how to check some user entered values in the onItemInserting event and cancel the item from being inserted. The reason I want to do it in the code behind is to query the database and use the values to validate the user entered data.
Pseudo Code is as follows:
protected void Form_addRoom_ItemInserting(object sender, FormViewInsertEventArgs e)
{
... Query DB for some values ...
if(enteredMaxPeople > queryMaxPeople)
{
**Cancel** DB Insert
statusLabel.text = "Value entered not valid";
}
}
In the end the question comes down to how do I cancel a FormView from inserting in the code behind?
Thank you!
Sean
e.Cancel = true;

Resources