I have a gridview that has the columns as below. These columns have textboxes with autopostback = true and need to get their value in RowDataBound of gridview. The problem is that when you type something in the textbox and take the focus off of it, occurs in the RowDataBound grid but the value entered is NOT captured (= /)
Help me to solve this problem, there is more to do. I can not use jquery or anything, only the TextChanged some textbox gridview to get the value.
Code:
<Columns>
<asp:TemplateField HeaderText="Entrada">
<ItemTemplate>
<asp:TextBox ID="txtEmanha_g" AutoPostback="true" class="Mask"
Width="40px" runat="server"
Text='<%#Eval("ENTRADA") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
You need to set your GridView up to be editable and avail of the EditItemTemplate. Here's a working example:
Editable Gridview with Textbox, CheckBox, Radio Button and DropDown List
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// Bind grid here only on page load not every post back to the server
}
}
Related
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.
What I'm trying to accomplish is when I click a button in my gridview, the values of that particular row must be displayed in textlabels lblID, lblName, ...
I just don't have a clue how to do it.
This is the code of my sqldatasource:
<asp:SqlDataSource ID="srcProd" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnDB %>"
ProviderName="<%$ ConnectionStrings:ConnDB.ProviderName %>"
SelectCommand="SELECT p.tProdID, p.tProdImage, p.tProdBeschrijving, m.tMerkNaam, m.tMerkImage, p.tProdVerkoop FROM tblProducten AS p INNER JOIN tblMerken AS m ON p.tMerkID = m.tMerkID ORDER BY m.tMerkNaam">
</asp:SqlDataSource>
This is a screenshot of the gridview I'm talking about.
When I press one of the buttons I would like e.g. the parameter ID displayed in lblID.
All help, hints and tips are appreciated.
Assign a CommandName (which is like "ShowDetails" or so) and a CommandArgument (which is the ID of the record) to the button. A click on the button will now trigger the grid's RowCommand event, passing you both CommandName and CommandArgument in e. Then fetch the record from your DB and populate your controls:
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Foo2" CommandArgument='<%# Eval("RowID") %>'
CommandName="ShowDetails" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Debug.WriteLine("Command Handler");
}
SO basicly this can be done on two ways:
Add a server-side click handler behind the button and update the label inside an UpdatePanel (this case we do not need a postback)
Add some javascript on the button's "OnClientClick" event to set this label... This method can be set in the GridView's bind method.
Hope this helps.
I have a GridView that displays data on three columns. On the third column I have a CheckBox. I have two things that I need to achieve
CheckBox will be checked based on the column value (1,0)
If it is checked the rest of the two columns should display #### However the data for the two columns should remain in the database.
How can this be achieved?
Can I find the CheckBox on RowDataBound event and check the value and make the CheckBox checked and unchecked? How about making the other columns ####?
NEW Comments:
string str = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[2].ToString();
this helps to set the checkbox checked or not.
if checked is true I am trying the following.
((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0] = "#####";
((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[1] = "#####";
((System.Data.DataRowView)(e.Row.DataItem)).Row.AcceptChanges();
It is displaying the gridview checkbox as checked but the column value is not changed to "####"
You can turn your item columns into TemplateColumns and do the following which will localize your code to the control level and you don't have to worry about all the searching. I pefer to never use the built in column types because there are usually future enhancements that require changing the columns to TemplateColumns anyways. It also gives you a lot of flexibiltiy on useage.
Here is an example:
<asp:GridView ID="grdYourGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="YourField1">
<ItemTemplate>
<asp:Literal runat="server" ID="ltYourField1"
OnDataBinding="ltYourField1_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="YourField2">
<ItemTemplate>
<asp:Literal runat="server" ID="ltYourField2"
OnDataBinding="ltYourField2_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="YourCheckBoxField">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkYourCheckBoxField"
OnDataBinding="chkYourCheckBoxField_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your codebehind implement each control's OnDataBinding:
protected void ltYourField1_DataBinding(object sender, System.EventArgs e)
{
Literal lt = (Literal)(sender);
lt.Text = (bool)(Eval("YourCheckBoxField")) ?
"##########" : Eval("YourField1");
}
protected void ltYourField2_DataBinding(object sender, System.EventArgs e)
{
Literal lt = (Literal)(sender);
lt.Text = (bool)(Eval("YourCheckBoxField")) ?
"##########" : Eval("YourField2");
}
protected void chkYourCheckBoxField_DataBinding(object sender, System.EventArgs e)
{
CheckBox chk = (CheckBox)(sender);
chk.Checked = (bool)(Eval("YourCheckBoxField"));
}
The advantages to doing it this way is your could replace code easily as it is all isolated and has no 'searching' for expected controls. I very rarely use the RowDataBound event because it makes you have to write specific code to look for the controls and it makes more sense to me to have the code localized to the control. If someone changes something they know there are ONLY affecting that one control instead of everything on the row possibly as a side effect. You could also use the <%# method and do the Evals right in the markup but I personally prefer to never have any code in the aspx markup at all.
I wanted to do a datagrid that had the allowed a user to edit current information as well as add new stuff. I also need it to have a checkbox in there that I can respond to. Basically it would be a name, and an isActive field that was represented by a checkbox in each row of the datagrid.
I would like to use linq for this but am not sure if it's even possible. This is a ASP.Net website.
If anyone had any feedback that would be awesome.
Easy enough to do.
The GridView has a number of events that you can use for certain operations (Delete, Edit, Cancel, and Update). For example, the OnRowUpdating and OnRowEditing would look like thus:
<asp:GridView ID="gvTest" runat="Server" OnRowUpdating="gvTest_RowUpdating" OnRowEditing="gvTest_RowEditing">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnUpdate" runat="Server" Text="Update" CommandName="Update">
<asp:Button ID="btnEdit" runat="Server" Text="Edit" CommandName="Edit">
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then implement the event handlers for the update (edit, delete, etc.) in your codebehind. To make life easier for yourself, you can switch over to Design view, find your GridView and bring up the Events (the icon that looks like a lightning bolt) and then double click an event and the stub of it will automatically be created for you in the codebehind and the html markup will automatically be created as well. An example of the RowUpdating event handler would look like thus:
protected void gvTest_RowUpdating(object sender, GridViewUpdateEventArgs e) {
// Convenient access to the row index that was selected
int theRowIndex = e.RowIndex;
GridViewRow gvr = gvTest.Rows[e.RowIndex];
// Now its just a matter of tracking down your various controls in the row and doing
// whatever you need to with them
TextBox someTxtBox = (TextBox)gvr.FindControl("theTextBoxID");
DropDownList someDDL = (DropDownList)gvr.FindControl("theDDL_ID");
// Perhaps some business class that you have setup to take the value of the textbox
// and insert it into a table
MyDoSomethingClass foo = new MyDoSomethingClass {
FirstName = someTxtBox.Text,
Age = someDDL.SelectedItem.Value
};
foo.InsertPerson();
}
Note that you can also use the OnRowCommand instead of using Update (Edit, Delete, etc.) events, but the OnRowCommand doesn't have the selected row index readily available for you. If you want it then you have to do a little magic in your markup.
<asp:Button ID="btnDoSomething" runat="Server" Text="Do Something" CommandArgument="<%# Container.DataItemIndex %>" CommandName="DoSomething">
And then in the RowCommand event you do something like this to get at the row index:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e) {
int rowIdx = Convert.ToInt32(e.CommandArgument);
}
EDIT:
Accessing the key(s) that your GridView is bound to is quite simple, actually. Assuming that your GridView is bound to only one key, you can get the key in this manner (assume that we're in the RowCommand event):
int rowIdx = Convert.ToInt32(e.CommandArgument);
int someKeyID = Convert.ToInt32(gvTest.DataKeys[rowIdx].Value);
<asp:Repeater ID="Cartridges" runat="server" onitemcommand="Cartridges_ItemCommand">
<ItemTemplate>
<p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox></p>
<div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" CommandArgument='<%#Eval("cartID") %>' Text="Buy"></asp:LinkButton></div>
</ItemTemplate>
</asp:Repeater>
Why does the TextBox cartQty only return the default value of 0 rather than the value entered and submitted? If I change the value to 3 it submits 3 regardless of what's typed.
Here's the codebehind for cartQty
LinkButton lb = (LinkButton)e.CommandSource;
int varCartQty = Convert.ToInt32(((TextBox)lb.Parent.FindControl("cartQty")).Text);
Thank you ;-)
I can only guess:
You are binding the Repeater to it's DataSource on every postback but not only if(!Page.IsPostBack)
I doubt your repeater is rebinded. When you click the button your page_load event is called before your click handler, where your repeater is binded.
So you need to take care of that.
if(!IsPostBack)
{
//Put repeater binding code here
}