Taking gridview value - c#

I want to save student ID which is being set in a GridView. I want to save each row student ID into table through model whose object name is "am".
for (int i = 0; i < GridView1.Rows.Count; i++)
{
am.Std_ID= GridView1.Rows[i]["Std_ID"];
}
By using above method it says you cannot use indexing with GridView. What should I do.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="FullName" HeaderText="Student Names"/>
<asp:TemplateField ItemStyle-HorizontalAlign = "Center">
<ItemTemplate>
<asp:TextBox runat="server" ID="marks" Width="30px" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My second question is in ItemTemplate I am using textbox. When I use its ID in function then Visual Studio says "marks doesn't exist in the current context". What should I do?

This will not exist: -
GridView1.Rows[i]["Std_ID"];
You don't access the data bound to a grid in this way; you need to reference the DataItem property.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewrow.dataitem(v=vs.110).aspx
However your requirement is quite common, you could add a HiddenField control to the itemtemplate to store your ID, and retrieve the control (and therefore its value) in a server-side method.

Related

Rowdeleteing event in Gridview

I have been trying to write this simple logic of deleting a row from the gridview and from the SQL database of the selected row, but keep getting a null reference to cell, which has the primary key [ID] in a field.
Here's my html:
<asp:GridView ID="grvInventoryEdit" runat="server" BackColor="White" onrowdeleting="grvInventoryEdit_RowDeleting"
onrowediting="grvInventoryEdit_RowEditing"
onrowupdating="grvInventoryEdit_RowUpdating">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" /><asp:TemplateField HeaderText="Id">
<ItemTemplate>
<%#Eval("No")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtEditNo" ReadOnly="True" Text='<%#Eval("No")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>........ </Columns> </asp:GridView>
And my back-end code for rowdeleting event is :
protected void grvInventoryEdit_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
TextBox id = (TextBox)grvInventoryEdit.Rows[e.RowIndex].FindControl("txtEditNo");
Asset asset = db.Assets.Single(a => a.No == Convert.ToInt32(id));
db.Assets.DeleteOnSubmit(asset);
db.SubmitChanges();
binddata();
}
and when the event fires, this is what i am seeing while debugging:
I am not sure why i am getting a null value ,though, there is a value for that cell.
Could you tell me what i am doing wrong ?
Regards,
Might be it is due to the readonly property of textbox, not suer.
If you want to use the image button for edit and delete then use
protected void ibtnDelete_Click(object sender, ImageClickEventArgs e)
{
GridViewRow gvRow = (GridViewRow)((ImageButton)sender).NamingContainer;
Int32 UserId = Convert.ToInt32(gvUsers.DataKeys[gvRow.RowIndex].Value);
// delete and hide the row from grid view
if (DeleteUserByID(UserId))
gvRow.Visible = false;
}
For complete code see
You are passing TextBox object instead instead of Text property of TextBox
Asset asset = db.Assets.Single(x=>x.No == Convert.ToInt32(id.Text));
and your TextBox is also coming null means it's unable to find it in GridView, try like this:
TextBox id = e.Row.FindControl("txtEditNo");
Also see this CodeProject article to understand how to use ItemTemplate and EditItemTemplate
why are you adding a second commandfield instead of just enabling the delete button on the existing one.
if you are using a command field you should be supplying an compatible datasource that provides Delete functionality
if you're "rolling your own" delete functionality then just use a regular Button control and supply a CommandName and CommandArgument, such as CommandName="MyDelete" CommandArgument=<row number> where <row number> is supplied via GridView RowDataBound() event.
Regardless of how you choose to implement Delete you should be placing the key field in the GridView DataKeys Property and not as a field within each row. This will make obtaining the PK far easier than what you are trying to do
I guess, in my HTML, i have only the value that's bound to the item, is being displayed, and there are no textboxes in my <ItemTemplate>, hence, it pulls null value. Whereas, in my <EditItemTemplate> there is a textbox, which can pull the value from the cell.
So I changed my HTML to this:
<asp:TemplateField HeaderText="Id">
<ItemTemplate>`<asp:label runat="server" ID="lblEditNo" ReadOnly="True" Text='<%#Eval("No")%>'></asp:label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtEditNo" ReadOnly="True" Text='<%#Eval("No")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
and no change in my codebehind, and this resolved the issue.

error on updating grid view values asp.net

I have usedgridView for update and delete data. But I'm getting
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index" error while updating.
There is no problem in your jquery datetimepicker
Problem seems to be in :
GridViewRow row = GridView1.Rows[e.RowIndex];
Simply take separate link buttons for edit and delete as:
<asp:TemplateField HeaderText="Edit" ItemStyle-Width="150">
<ItemTemplate>
<asp:linkbutton id="lnkEdit" runat="server" CommandName="Edit" Text="Edit"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" ItemStyle-Width="150">
<ItemTemplate>
<asp:linkbutton id="lnkDelete" runat="server" CommandName="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
I can see you are using dropdownlist for copy_id so it is better to use the below code to find the dropdownlist and fetch value from it.
DropDownList lblCopyDdl= (DropDownList )GridView1.Rows[e.RowIndex].FindControl("lblCopyId");
int Copy_Id = Convert.ToInt32(lblCopyDdl.selectedvalue);
Recommendation::
Better if you use the same code as mentioned above for other fields for getting value..
for eg
int Borrower_Id = Convert.ToInt32((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBorrowerId").Text);
Update::
If it not works then do check your e.RowIndex as mentioned in Ángel Di María's answer.
Update 2
try to fetch the date field like this
DateTime Date_Borrowed = Convert.ToDateTime((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDateBorrowed").Text);
and
DateTime Date_Returned= Convert.ToDateTime((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtDateReturned").Text);
It seems that you are trying to read a cell value using index but there is no data element at that position. Suggest you to do debug and increment index value in your collection in watch window and observe data

DataBind and DataSource on a Gridview

I have done gridviews before, where I bind all SQL data from data safe reader or specify column names and binds at the javascript level. This is a bit different and I am a bit stumped on how to proceed.
I have a business class that handles all SQL data queries.
This class is called to Fetch a LIST. This list contains collections and child collections.
var _InfoList = BusinessObjectClass.Get(_CriteriaKey);
I can access the list as such:-
Txtbox1.Text = _InfoList.ID#.ToString();
Now I am trying to bind one of the collections in the LIST to a gridview.:-
C#:-
gvwMembers.DataSource = _InfoList.Members;
gvwMembers.DataBind();
Where Members is a collection...
But this syntax doesn't add any thing to the gridview...The gridview is empty.
Second methodology:-
I also tried doing something like this:-
List<BusinessObjectClass> Members = new List<BusinessObjectClass>();
Members = _InfoList.Members;
gvwVendors.DataSource = Members;
gvwVendors.DataBind();
But to no avail.. this is because the problem lies in the 2nd statement:-
Members = _InfoList.Members.... this is not a valid assignment...can anyone help with this?
After fleshing out some details in the comments, it is perfectly fine to have a simple GridView with no columns defined, but make sure AutoGenerateColumns is not false. The default is true. This will create a column for you, based on each property of the object being bound.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">
</asp:GridView>
And in order to pick and choose which properties to display, define them in the <Columns> section.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Property1" HeaderText="Property1" />
<asp:TemplateField HeaderText="Property2">
<ItemTemplate>
<asp:Label ID="lblProperty2" runat="server" Text='<%# Eval("Property2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

how to find out the selected row in a gridview

I am doing a project in .net with c#. in that there is a registration form of new users into the site. admin should approve the registration. for that I'm using a GridView. How to find out the selected row in the grid view?
Use the GridView.SelectedRow property.
Alternatively, you can get the index of the selected row with the GridView.SelectedIndex property.
are you perhaps referring to a DATAGRIDVIEW?
if so, to find the content of a certain column of the selected row
datagridviewname.item(0, datagridviewname.currentrow.index).value
where 0 = first column of your datagrid
Use following gridview property>
gvTradeFile.SelectedRows[0].Cells[10].Value.ToString();
Hope this will help you.
Normally I use RowCommand for this type of thing:
<asp:GridView runat="server" id="gvUsers" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="username" HeaderText="Username" />
<asp:BoundField DataField="dateregistered" HeaderText="Date" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" id="lnkApprove" CommandName="Approve" CommandArgument='<%# Eval("userid") %>' Text="Approve"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" id="lnkDeny" CommandName="Deny" CommandArgument='<%# Eval("userid") %>' Text="Deny"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now you need to pass instructions through on RowCommand...
private void gvUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Approve":
// Executes code to update the users table,
// setting the approved flag to true
// Usage: ApproveUser(integer userid);
ApproveUser(e.CommandArgument);
break;
case else:
// do whatever if the user registration wasn't approved
break;
}
}
The switch is a good idea in case you need to do a few things with the data here. It evaluates the primary key value for the row (in this case, that's the value of the userid column in the database) for the selected row (automatically determined when you click the link) along with the CommandName to tell it what to do with that information.
Hope this helps.

Troubles retrieving data from within OnRowCommand from a GridViews

If I have this <asp:ButtonField runat="server" DataTextField="Name" CommandName="GetName"></asp:ButonField> Within a GridView. Is there any way to retrieve the DataTextField (Name) from the OnRowCommand method?
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True" AutoGenerateColumns="False"
DataSourceID="ObjectDataSource_Names"
DataKeyNames="ID,ModuleId" OnRowCommand="ChangeName">
Or alternatively, is there any way to make CommandName into an attribute where the command is dynamically entered based on given data, similar to the difference between DataTextField vs TextField.
I added <asp:BoundField DataField="Name" /> Then you can retrieve it using the same method here: GridView.onRowCommand Method
All I need to do now is find out a way to hide the field. If anyone knows how to, please let me know. Visible="false" gets rid of the field all together...
Not really sure if this is the best way, but it works:
Make your column a templatefield and bind the name value to a asp:hiddenfield control:
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hfName" runat="server" Value='<%# Eval("Name") %>'>
</asp:HiddenField>
</ItemTemplate>
</asp:TemplateField>

Categories

Resources