Need help in radiobutton within gridview - asp.net

Thru radio button i am selecting the data from gridview. Here all radio buttons are selectable at a time. Actually it should not happen at a time user can select only one button which i could not do. My second problem is when i am selecting particular radiobutton that details should be displayed in text box. I have Itemid, ItemName, Quantity, Rate and Total field in gridview. These values i have inserted thru textbox so i have all the corresponding text box for all. So once i select particular radiobutton those details should be displayed in corresponding textbox. I have done the insertion coding for this but couldn't do selecting thru radiobutton and dispalying in textbox. Pls somebody help me in coding for this problem.
Thanks,
sumit

Sumit,
Don't use the html control, use the asp control:
<asp:RadioButton ID="RadioSelector" runat="server" GroupName="RadioSelectors" />
I had a similar problem in an ASP.NET class, and I followed this tutorial which worked perfectly.

Sounds like the classic master/detail pattern see here:
Tutorial 10: Master/Detail Using a Selectable Master GridView with a Details DetailView
You are fighting the intended workings of ASP.NET databound controls by using radio buttons. I don't like having select links either they're not exactly Web 2.0! but they can be quite easily replaced with a row click by doing this (or variation of same):
Select a row in an asp:GridView without using a Select Command

I read several articles on the net but none were suitable. I finally figured out my own solution without using either HTMLControls radiobutton nor using Javascript. This works for my requirement.
My Gridview html settings were as follows
<asp:GridView ID="grdVersion" runat="server"
AutoGenerateColumns="false" AllowPaging="true"
AutoGenerateEditButton="false" PageSize="10" Width="400px"
EmptyDataText="No records available."
OnRowDataBound="grdVersion_RowDataBound"
AutoGenerateSelectButton="false">
<Columns>
<asp:BoundField DataField="versionid" HeaderText="Version No." ItemStyle-Width="50px"
ItemStyle-Wrap="false" HtmlEncode="true" ReadOnly="true" />
<asp:BoundField DataField="version_date" HeaderText="Version Date" ItemStyle-Width="100px"
ItemStyle-Wrap="false" HtmlEncode="true" ReadOnly="true" />
<asp:BoundField DataField="remarks" HeaderText="Remarks" ItemStyle-Width="150px"
ItemStyle-Wrap="true" HtmlEncode="true" ReadOnly="true" />
**<asp:TemplateField HeaderText="Admin" HeaderStyle-Width="100px">
<ItemTemplate>
<asp:RadioButton ID="rdCurrent" runat="server"
Checked="false" Enabled="true" GroupName="rgVersion"
AutoPostBack="true"
OnCheckedChanged="rdCurrent_CheckChanged" />
</ItemTemplate>**
</asp:TemplateField>
</Columns>
</asp:GridView>
The server code (C#) was as follows,
DataTable dtDataSpaceVersions; //place this inside the codebehind page class
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dtDataSpaceVersions = ListDataSpaceVersions();
ViewState["dtDataSpaceVersions"] = dtDataSpaceVersions;
PopulateGridVersion();
}
}
protected void PopulateGridVersion()
{
grdVersion.DataSource = dtDataSpaceVersions;
grdVersion.DataBind();
}
protected void rdCurrent_CheckChanged(object sender, EventArgs e)
{
Control selectedVersion = ((Control)sender).Parent;
if (ViewState["dtDataSpaceVersions"] != null)
dtDataSpaceVersions = (DataTable)ViewState["dtDataSpaceVersions"];
foreach (DataRow dtr in dtDataSpaceVersions.Rows)
{
if (dtr["versionid"].ToString() == ((System.Web.UI.WebControls.GridViewRow)selectedVersion.Parent).Cells[0].Text)
dtr[3] = "Y";
else
dtr[3] = "N";
}
PopulateGridVersion();
}
protected void grdVersion_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv;
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
{
drv = (DataRowView)e.Row.DataItem;
if ((RadioButton)(e.Row.FindControl("rdCurrent")) != null)
if (drv.Row.ItemArray[3].ToString() == YesNo.N.ToString())
((RadioButton)(e.Row.FindControl("rdCurrent"))).Checked = false;
else
((RadioButton)(e.Row.FindControl("rdCurrent"))).Checked = true;
//setGridUserPermissionCheckBoxState(e.Row, drv);
}
}
public DataTable ListDataSpaceVersions()
{
string sql = string.Empty;
DataTable dt = new DataTable();
dt.Columns.Add("versionid", typeof(String));
dt.Columns.Add("version_date", typeof(String));
dt.Columns.Add("remarks", typeof(String));
dt.Columns.Add("is_current", typeof(String));
DataRow dtr;
dtr = dt.NewRow();
dtr[0] = "1.1";
dtr[1] = "12-Dec-2005";
dtr[2] = "Campaign Information";
dtr[3] = "N";
dt.Rows.Add(dtr);
dtr = dt.NewRow();
dtr[0] = "1.2";
dtr[1] = "06-Mar-2006";
dtr[2] = "Sales corrections";
dtr[3] = "N";
dt.Rows.Add(dtr);
dtr = dt.NewRow();
dtr[0] = "1.3";
dtr[1] = "24-Aug-2009";
dtr[2] = "Invoice reconciliation";
dtr[3] = "Y";
dt.Rows.Add(dtr);
dtr = dt.NewRow();
dtr[0] = "1.4";
dtr[1] = "30-May-2010";
dtr[2] = "Invoices verification";
dtr[3] = "N";
//dtr[0][0] = "";
dt.Rows.Add(dtr);
return dt;
}

Related

how to change the gridview row value after button click event

I have a table in four columns see screenshot here:
But I need two columns in that table name and gender see screenshot here:
Display in this type but I have required after click the button row value will change in GridView button out side in GridView e.g. row value 1,2 can instead male and female that is my requirement.
You need to fetch that data from database in dataset or datatable and assign that as DataSource to the GridView and call DataBind on that GridView. Now in RowDataBound event compare the value and assign value to UI label / literal based on that.
Below is GridView in aspx page.
<asp:GridView runat="server" AutoGenerateColumns="false" ID="GridView1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Literal ID="ltrlEmpName" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Gender">
<ItemTemplate>
<asp:Literal ID="ltrlEmpGender" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In code behind, lets say you want to assign the datasource to this GridView in page load or any other method. Below will be its code. Note that in sample here I have taken dummy DataTable and filled values for simplicity, you need to fill that DataTable from db values.
protected void Page_Load(object sender, EventArgs e)
{
// Dummy data table below, that needs to be replaced by datatable / dataset fetched from database.
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpName", typeof(string)));
dt.Columns.Add(new DataColumn("EmpGender", typeof(int)));
DataRow dr1 = dt.NewRow();
dr1["EmpName"] = "Romesh";
dr1["EmpGender"] = 1;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["EmpName"] = "Sandya";
dr2["EmpGender"] = 2;
dt.Rows.Add(dr2);
// Bind the datasource to gridview.
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
System.Web.UI.WebControls.Literal ltrlEmpName = (System.Web.UI.WebControls.Literal)e.Row.FindControl("ltrlEmpName");
System.Web.UI.WebControls.Literal ltrlEmpGender = (System.Web.UI.WebControls.Literal)e.Row.FindControl("ltrlEmpGender");
// Bind employee name to its label.
ltrlEmpName.Text = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpName"));
// Bind employee gender to its label based on its value.
if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpGender")) == "1")
{
ltrlEmpGender.Text = "Male";
}
else if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "EmpGender")) == "2")
{
ltrlEmpGender.Text = "Female";
}
else
{
ltrlEmpGender.Text = "Other";
}
}
}
You will get out as Table as below.

Stop Textbox in GridView Losing Data on Postback

I have a GridView which I dynamically add rows to through the button_OnClick event, this adds a new row with the Product name & Product ID from a DropDownList and also contains a column with an empty text box for user input.
My problem is that when I test it and enter data in the text box, then add another Product, the post back causes my data to be lost (the correct number of rows are still there with product names / ids).
<asp:GridView runat="server" ID="grdSelectedProducts" BorderWidth="1px" CellPadding="3" CellSpacing="2" AutoGenerateColumns="False" OnRowDataBound="grdSelectedProducts_OnRowDataBound" ShowHeaderWhenEmpty="True" DataKeyNames="ProductId"
OnRowCommand="grdSelectedProducts_RowCommand" OnRowDeleted="grdSelectedProducts_RowDeleted" OnRowDeleting="grdSelectedProducts_RowDeleting" EmptyDataText="Please select a Product and click 'Add'" EnableViewState="True">
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" ReadOnly="False"/>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDescriptionEntry" Text="" style="width:98% !important" EnableViewState="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="linkDelete" runat="server" CommandName="Delete" CommandArgument="<%# Container.DataItemIndex %>">Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductId" HeaderText="ProductId" ReadOnly="False" Visible="False" />
</Columns>
</asp:GridView>
How can I avoid postback scrapping the data on each txtDescriptionEntry that is created? There could be between 0 and an infinite number of these text boxes, so I won't have exact names at any one time.
Edit, as per a comment below I'm including the code for how I add rows to the grid:
private DataTable ProductDataTable
{
get {return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
set { ViewState["ProductDataTable"] = value; }
}
private DataTable CreateDataTable(bool isAddingValue, string selectedProduct, string selectedId)
{
// if isAddingValue is FALSE then it isn't from a button click to add a Product, it is just
// a call to create the datatable
DataTable dataTable = ProductDataTable;
if (!dataTable.Columns.Contains("Product"))
{
dataTable.Columns.Add("Product");
dataTable.Columns.Add("Description"); // This column is free format text that the user enters.
dataTable.Columns.Add("ProductId");
}
if (isAddingValue)
{
// Get the data from ViewState
//dataTable = ProductDataTable;
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataRow["ProductId"] = selectedId;
dataTable.Rows.Add(dataRow);
}
else
{
grdSelectedProducts.DataSource = null;
grdSelectedProducts.DataSource = ProductDataTable;
grdSelectedProducts.DataBind();
}
// Save the data back to ViewState
ProductDataTable = dataTable;
return dataTable;
}
protected void btnAddProduct_OnClick(object sender, EventArgs e)
{
string selectedProduct = ddlProduct.SelectedItem.Text;
string selectedId = ddlProduct.SelectedValue;
DataTable dataTable = CreateDataTable(true, selectedProduct, selectedId);
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
}
protected void grdSelectedProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
DataTable table = CreateDataTable(false, string.Empty, string.Empty);
table.Rows.RemoveAt(rowIndex);
grdSelectedProducts.DataSource = table;
grdSelectedProducts.DataBind();
}
}
}
And in the Page_Load event, if it isn't a PostBack there is also binding of an empty list
grdSelectedProducts.DataSource = new List<Products>();
grdSelectedProducts.DataBind();
I figured this out, not the nicest solution (so I probably wouldn't recommend it) but it got me out of a jam.
I used the OnRowDataBound event so for each row that was being bound to the table I would use the RowIndex to get the appropriate row in the DataTable, I would then assign the text box (also obtained via the index) the value from the DT. Example below.
protected void grdSelectedproducts_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
TextBox txtDescription = e.Row.FindControl("txtDescriptionEntry") as TextBox;
if (txtDescription != null)
{
DataTable dt = ProductDataTable;
DataRow row = dt.Rows[e.Row.RowIndex] as DataRow;
txtDescription.Text = row[1].ToString();
}
}
}

how to delete a row in gridview if using template field

I have tried so many times but i am not able to delete a row in GRID VIEW. I didn't create any database.I am just storing all the values of the text field in the GRID VIEW.If i want to delete a row in the GRID VIEW using template field button means,what will be the solution.
This is the way i am storing and populating values in GridView.
DataSet ds = new DataSet();
DataRow dr = ds.Tables[0].NewRow();
dr[0] = lbltxtcustomer.Text;
dr[1] = FNtxt.Text;
dr[2] = LNtxt.Text;
dr[3] = DrpdownMonth.Text + "/" + DrpdownDay.Text + "/" + DrpdownYear.Text;
dr[4] = lbltxtage.Text;
dr[5] = txtEmail.Text;
dr[6] = TxtPhone.Text;
dr[7] = Txtlocation.Text;
ds.Tables[0].Rows.Add(dr);
BindGrid()
;
Try This
HTML Markup
Below is the HTML Markup of the APS.Net GridView. Here I am making use the CommandFieldand OnRowDeleting event to delete the GridView Row. Hence I will apply the JavaScript Confirmation Box to the CommandFieldDelete Button itself.
<asp:GridView ID="GridView1" CssClass = "Grid" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
Applying the JavaScript Confirmation Box to the GridView CommandField
Delete Button
To apply the JavaScript Confirmation Box, I am looking for the Button in the Controls of the GridView Cell Index 2 since it has the CommandField. Once
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string item = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
}
}
}
}
Delete the ASP.Net GridView Row using CommandField and OnRowDeleting
event
Below is the code to delete the ASP.Net GridView Row using OnRowDeleting event
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[index].Delete();
ViewState["dt"] = dt;
BindGrid();
}

Telerik RadGrid with different types of edit controls

I have to dispay a list of fields. Some are editable and some are not. Those that are can be different types, such as text fields, dates, times, or boolean. I'm using Telerik's RadGrid. See screen shot for a test project I made.
Questions:
In the item created handler, why are there 4 cells? I had to fill in cells[2] and cells[3] for the values to display. I set AutoGenerateColumns to false, and I only have two GridTemplateColumn definitions.
Why does the item.RowIndex incrment by two's and go up to twenty? When I have 10 rows.
Is there a better way to do this?
Here's how I declared the grid:
<telerik:RadGrid runat="server" ID="Grid1" Width="100%" Height="500px" GridLines="None" AutoGenerateColumns="false"
OnItemCreated="OnGridItemCreated"
OnNeedDataSource="OnGridNeedDataSource">
<ItemStyle Wrap="true" />
<AlternatingItemStyle Wrap="true" />
<ClientSettings>
<Selecting AllowRowSelect="false" />
<Scrolling AllowScroll="true" UseStaticHeaders="true" />
<Resizing AllowColumnResize="true" ClipCellContentOnResize="true" ResizeGridOnColumnResize="true" EnableRealTimeResize="true" />
</ClientSettings>
<MasterTableView>
<NoRecordsTemplate>
<asp:Label ID="lblNorec1" runat="server" Text="No records"></asp:Label>
</NoRecordsTemplate>
<Columns>
<telerik:GridTemplateColumn UniqueName="FieldDisplayName" HeaderText="Field Name">
<ItemTemplate>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn UniqueName="FieldValue" HeaderText="Value">
<ItemTemplate>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
/
/ grid needs datasource
protected void OnGridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
// create a DataSource
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Field_Display_Name"));
dt.Columns.Add(new DataColumn("Field_Value"));
for (int i = 0; i < 10; ++i)
{
DataRow dr = dt.NewRow();
dr["Field_Display_Name"] = "Item Id" + i.ToString();
dr["Field_Value"] = "Value" + i.ToString();
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Grid1.DataSource = ds;
}
// grid item is created
protected void OnGridItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = (GridDataItem)e.Item;
// fill in cells 2 and 3. Why are there 4?
Label lbl = new Label();
lbl.Text = "Field " + item.RowIndex;
item.Cells[2].Controls.Add(lbl);
switch (item.RowIndex)
{
case 2:
case 8:
RadTextBox txt = new RadTextBox();
txt.ID = "RadTextBox1";
txt.Text = "hello " + item.RowIndex;
item.Cells[3].Controls.Add(txt);
break;
case 4:
case 10:
RadDatePicker dp = new RadDatePicker();
dp.ID = "RadDatePicker1";
dp.SelectedDate = DateTime.Now;
item.Cells[3].Controls.Add(dp);
break;
case 6:
case 12:
CheckBox cb = new CheckBox();
item.Cells[3].Controls.Add(cb);
break;
default:
Label lbl2 = new Label();
lbl2.Text = "Value " + item.RowIndex;
item.Cells[3].Controls.Add(lbl2);
break;
}
}
}
If the grid reflects your actual needs, I would suggest you go with an HTML table inside an ASP FormView. You can map out most of the things you've shown here right in the HTML. There are plenty of FormView tutorials out there, it looks like more of a solution for what you're after. Don't let the complexity of trying to squeeze that stuff into a radgrid get you going in the wrong direction.
If you want to show say 10 records at a time, that's where the gridview/radgrid comes in handy, if it's just one record at a time, look to the formview.
EDIT: I just noticed this was asked like a year ago. I hope you aren't still waiting on an answer for this one!

Show combo on AspxGridview

I work on northwind database. In my AspxGridview I want to show comboBox. I fill grid on back end C# I also want my combo will fill back end.
<dxwgv:ASPxGridView ID="ASPxGridView1" runat="server"
AutoGenerateColumns="False" KeyFieldName="CategoryID"
oncelleditorinitialize="ASPxGridView1_CellEditorInitialize">
<Columns>
<dxwgv:GridViewCommandColumn VisibleIndex="0" Width="80px">
<EditButton Visible="True">
</EditButton>
<NewButton Visible="True">
</NewButton>
<DeleteButton Visible="True">
</DeleteButton>
</dxwgv:GridViewCommandColumn>
<dxwgv:GridViewDataTextColumn Caption="CategoryID" FieldName="CategoryID"
VisibleIndex="1">
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataComboBoxColumn Caption="CategoryName"
FieldName="CategoryName" VisibleIndex="2">
<PropertiesComboBox TextField="Value" ValueField="key" ValueType="System.Int32">
<ClientSideEvents SelectedIndexChanged="function(s, e) { OnBankChanged(s); }" />
</PropertiesComboBox>
</dxwgv:GridViewDataComboBoxColumn>
<dxwgv:GridViewDataTextColumn Caption="Description" FieldName="Description"
VisibleIndex="3">
</dxwgv:GridViewDataTextColumn>
</Columns>
</dxwgv:ASPxGridView>
To fill grid i use the bellow C# syntax.
DataClasses1DataContext db = new DataClasses1DataContext();
var r = from p in db.Categories
select p;
ASPxGridView1.DataSource = r;
ASPxGridView1.DataBind();
To fill gridview cell of combo i use Bellow C# syntax
protected void ASPxGridView1_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
{
if (!ASPxGridView1.IsEditing || e.Column.FieldName != "CategoryID") return;
ASPxComboBox combo = e.Editor as ASPxComboBox;
if (!(e.KeyValue == DBNull.Value || e.KeyValue == null)) //return;
{
object val = ASPxGridView1.GetRowValuesByKeyValue(e.KeyValue, "CategoryID");
if (val == DBNull.Value) return;
Int32 CategoryID = (Int32)val;
FillCityCombo(combo, CategoryID);
}
combo.Callback += new CallbackEventHandlerBase(cmbBranch_OnCallback);
}
private void cmbBranch_OnCallback(object source, CallbackEventArgsBase e)
{
FillCityCombo(source as ASPxComboBox, Convert.ToInt16(e.Parameter));
}
protected void FillCityCombo(ASPxComboBox cmb, Int32 CategoryID)
{
//cmb.Items.Clear();
//cmb.DataSourceID = "";
DataClasses1DataContext db = new DataClasses1DataContext();
var r = from p in db.Categories
select new { p.CategoryID,p.CategoryName};
cmb.DataSource = r;
cmb.DataBind();
}
When I run the code AspxGridview fill well but when I click on Edit or New Command on left side of my grid shows me error message below:
**Object reference not set to an instance of an object.**
What's the problem?
How to solve this problem?
How to bind cell combo on aspx gridview?
This is the cause of this issue. You are checking for the "CategoryID" field name. But the ComboBox column is created for the "CategoryName" field:
if (!ASPxGridView1.IsEditing || e.Column.FieldName != "CategoryID") return;
ASPxComboBox combo = e.Editor as ASPxComboBox;
We've posted a sample project showing how to implement dependent combos in insert mode at:
http://www.devexpress.com/Support/Center/ViewIssue.aspx?issueid=Q102130
I hope, this project will be helpful to you.
Bind in the OnRowDataBound event (or AspxGridview equivalent)

Resources