I have radio buttons which I need to keep selected between pages. I have looked up all solutions but I am still confused on what I should do.
I will supply the code which shows you the functions of the radio buttons
.aspx page
<p>What Is Your Budget?
<asp:RadioButton ID="High_B" GroupName="Budget" runat="server" Text="High"
oncheckedchanged="High_B_CheckedChanged" ViewStateMode="Enabled"
AutoPostBack="True">
</asp:RadioButton>
<asp:RadioButton ID="Low_B" GroupName="Budget" runat="server" Text="Low"
oncheckedchanged="Low_B_CheckedChanged" AutoPostBack="True"
ViewStateMode="Enabled">
</asp:RadioButton>
</p>
<p>What is the level of excitement around FWC 2014?
<asp:RadioButton ID="High_E" GroupName="Radio" runat="server" Text="High"
oncheckedchanged="High__E_CheckedChanged" ViewStateMode="Enabled"
AutoPostBack="True">
</asp:RadioButton>
<asp:RadioButton ID="Low_E" GroupName="Radio" runat="server" Text="Low"
oncheckedchanged="Low_E_CheckedChanged" AutoPostBack="True"
ViewStateMode="Enabled">
</asp:RadioButton></p>
.aspx.cs page
public void Chart()
{
if (High_E.Checked && High_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/HighBud_Ex.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "High";
setName();
}
if (High_E.Checked && Low_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/LowBud_HighEx.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "LowHigh";
setName();
}
if (Low_E.Checked && High_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/HighBud_LowEx.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "HighLow";
setName();
}
if (Low_E.Checked && Low_B.Checked)
{
DataSet dSet = new DataSet();
dSet.ReadXml(Server.MapPath("~/ChartData/LowBud_Ex.xml"));
Chart1.DataSource = dSet.Tables[0];
Chart1.DataBind();
Session["name"] = "Low";
setName();
}
You should preserve the state of your radioButtons between postbacks. That is, in oncheckedchanged event, save the state of your radiobutton in a Session for example, and after postback, set back those states.
i too had this problem,i used session variable to store the state of radio buttons,what i did is at postback.I stored the state of radio buttons in a string seprated by comma and then when i needed to restore the state .i used the string split function to take the values in array n dependind on the string i restored the state of the controls
Related
I currently have two dropdown lists and they are populated with names from a database. What I want to do is have a player be selected, and then on a button click, the data from the table is populated into a gridview. Right now I am just getting a "No data returned" message and I cannot figure out why.
<asp:DropDownList ID="ddl_QB1" runat="server" Width="200px" AppendDataBoundItems="True"
AutoPostBack="True" Height="16px" DataTextField="Player" DataValueField="id" ></asp:DropDownList>
<asp:Gridview ID="GridView1" runat="server" AutoGenerateColumns="false" Visible="true"
BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px"
CellPadding="4" GridLines="Horizontal" ShowHeaderWhenEmpty="True" EmptyDataText="No records Found">
<Columns>
<asp:TemplateField HeaderText="Total Points">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("[Pts]") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Pts") %>'>
</asp:Label>
</ItemTemplate>
protected void Page_Load(object sender, EventArgs e)
{
LoadQuarterbacks();
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("select [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] from Quarterbacks", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
ddl_QB1.DataSource = dt;
ddl_QB1.DataBind();
}
}
private void LoadQuarterbacks()
{
ddl_QB1.Items.Clear();
ddl_QB2.Items.Clear();
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand("SELECT id, Player FROM Quarterbacks", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("Quarterbacks");
da.Fill(ds); // fill dataset
ddl_QB1.DataTextField = ds.Tables[0].Columns["Player"].ToString(); // text field name of table dispalyed in dropdown
ddl_QB2.DataTextField = ds.Tables[0].Columns["Player"].ToString();
ddl_QB1.DataValueField = ds.Tables[0].Columns["id"].ToString();
ddl_QB2.DataValueField = ds.Tables[0].Columns["id"].ToString(); // to retrive specific textfield name
ddl_QB1.DataSource = ds.Tables[0];
ddl_QB2.DataSource = ds.Tables[0];
ddl_QB2.DataBind();//assigning datasource to the dropdownlist
ddl_QB1.DataBind(); //binding dropdownlist
con.Close();
ddl_QB1.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
ddl_QB2.Items.Insert(0, new ListItem("--Select QuarterBack--", "0"));
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connectionstring);
string query = "SELECT [id], [Player], [Pts], [Att], [Cmp], [Yds], [TD] FROM Quarterbacks where id=" + ddl_QB1.SelectedValue;
SqlDataAdapter sda = new SqlDataAdapter(query,con);
con.Open();
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Following 3 changes would give desired results.
First - AutoPostBack should be set to false on the dropdown element as that is causing postback even before you click on the button.
Second - remove the current code inside if(!Page.IsPostback). This code is not necessary. Also, this code is not setting DataTextField and DataValueField properties for ddl_QB1 and ddl_QB2.
Third - put the method call LoadQuarterbacks() inside if(!Page.IsPostback). We do not have to bind these values for ddl_QB1 and ddl_QB2 on each request.
If a refresh is required on the dropdown controls, then call LoadQuarterbacks() method after binding the gridview at the end of the button click. That way you are capturing the selected values from dropdown before rebinding the them. Rebinding the DropDowns would cause them loose the selected values.
I have 2 dropdownlist on my web form and the second one is synchronised with the first one based upon what value has been chosen.
Everything works well between the 2 of them and am able to use the values from them to carry out my function.
However the first dropdownlist seems to have an effect on my repeater and paginations. Basically it keeps incrementing the pageddatesource and clears the repeater of any data ?
The SelectedIndexChanged is only meant to update the update.panel1 where the second dropdownlist is but then am not sure how it further increments the page numbers and removes data from repeater?
Here is the front end with the dropdownlists.
<section id="section-search">
<div class="fleft">
Start Date:
<asp:TextBox runat="server" ID="txtStartDate" CssClass="txt txt-sml"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="calStartDate" runat="server" PopupPosition="Right" Animated="true" TargetControlID="txtStartDate" />
End Date:
<asp:TextBox runat="server" ID="txtEndDate" CssClass="txt txt-sml"></asp:TextBox>
<ajaxToolkit:CalendarExtender runat="server" ID="calEndDate" PopupPosition="Right" Animated="true" TargetControlID="txtEndDate"></ajaxToolkit:CalendarExtender>
<hr />
Product Class:
<asp:DropDownList ID="drpProductClass" runat="server" Width="230px" OnSelectedIndexChanged="drpProductClass_SelectedIndexChanged" AutoPostBack="true" />
<hr />
<asp:UpdatePanel ID="updatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
Product:
<asp:DropDownList ID="drpProduct" runat="server" Width="230px" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="fright">
<asp:Button runat="server" ID="btnFilter" Text="Search" CssClass="submit" OnClick="btnFilter_Click"/>
</div>
</section>
<section id="section-title">
<h1>Order Search</h1><h2></h2>
</section>
<section class="info-strip tr">
<asp:Literal ID="litResults" runat="server"></asp:Literal>
</section>
<section class="track-table">
<asp:Literal runat="server" ID="litMessage" Visible="false" Text="<div class='wysiwyg'><p>You currently have no orders...</p></div>"></asp:Literal>
<asp:PlaceHolder runat="server" ID="phOrders">
<%--<table>
<thead>
</thead>
<tbody>--%>
<asp:Repeater ID="rprOrders" runat="server" OnItemCommand="rprOrders_ItemCommand" >
Here is my Code behind
protected void SetupControl()
{
if (this.StopProcessing)
{
// Do not process
}
else
{
if (CMSContext.ViewMode == ViewModeEnum.LiveSite)
{
if(!Page.IsPostBack)
{
PopulateProductClass();
PopulateProduct();
PopulateOrders();
}
}
}
}
protected void drpProductClass_SelectedIndexChanged(object sender, EventArgs e)
{
CustomTableItemProvider ctip = new CustomTableItemProvider();
UserInfo user = CooneenHelper.GetUserImpersonisationUser();
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#UserID", user.UserID);
DataSet ds = gc.ExecuteQuery("CN_GetEmpIDByUID", qdp, QueryTypeEnum.StoredProcedure, true);
int emplID = Convert.ToInt32(ds.Tables[0].Rows[0]["UserEmployeeID"].ToString());
if (drpProductClass.SelectedValue.ToString() != "0")
{
QueryDataParameters qdp2 = new QueryDataParameters();
qdp2.Add("#WR_ClassID", Convert.ToInt32(drpProductClass.SelectedValue.ToString()));
qdp2.Add("#UserEmployeeID", emplID);
DataSet ds2 = gc.ExecuteQuery("CN_OrdersGetProductByClassID", qdp2, QueryTypeEnum.StoredProcedure, true);
drpProduct.ClearSelection();
drpProduct.DataSource = ds2.Tables[1];
drpProduct.DataTextField = "ProductName";
drpProduct.DataValueField = "SKUNumber";
drpProduct.DataBind();
drpProduct.Items.Insert(0, new ListItem("-- Select Product --", "0"));
updatePanel1.Update();
}
else
{
drpProduct.ClearSelection();
PopulateProduct();
}
}
private void PopulateOrders()
{
CustomerInfo ki = CustomerInfoProvider.GetCustomerInfoByUserID(CooneenHelper.GetUserImpersonisationID());
int nKustomerID = ki.CustomerID;
DataTable dts = new DataTable();
dts.Columns.Add("OrderDate", typeof(string));
dts.Columns.Add("OrderNumber", typeof(string));
dts.Columns.Add("OrderItemSKUName", typeof(string));
dts.Columns.Add("OrderItemSKUID", typeof(string));
dts.Columns.Add("OrderItemStatus", typeof(string));
dts.Columns.Add("OrderItemUnitCount", typeof(string));
QueryDataParameters qdp = new QueryDataParameters();
qdp.Add("#CustomerID", nKustomerID);
DataSet ds = gc.ExecuteQuery("CN_OrderList", qdp, QueryTypeEnum.StoredProcedure, true);
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow drNew = dts.NewRow();
drNew["OrderDate"] = ValidationHelper.GetDateTime(dr["OrderDate"], DateTime.Now).ToShortDateString();
drNew["OrderNumber"] = dr["OrderNumber"].ToString();
drNew["OrderItemSKUName"] = dr["OrderItemSKUName"].ToString();
drNew["OrderItemSKUID"] = dr["OrderItemSKUID"].ToString();
drNew["OrderItemStatus"] = dr["OrderItemStatus"].ToString();
drNew["OrderItemUnitCount"] = dr["OrderItemUnitCount"].ToString();
dts.Rows.Add(drNew);
}
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dts.DefaultView;
//DataView view = dts.DefaultView;
//allow paging, set page size, and current page
pds.AllowPaging = true;
pds.PageSize = PerPage;
pds.CurrentPageIndex = CurrentPage;
//show # of current page in label
if (pds.PageCount > 1) litResults.Text += " - Showing page " + (CurrentPage + 1).ToString() + " of " + pds.PageCount.ToString();
//disable prev/next buttons on the first/last pages
btnPrev.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
rprOrders.Visible = true;
rprOrders.DataSource = pds;
rprOrders.DataBind();
}
We had a similar problem and could never figure out the root cause of it, we chalked it up to a bug in WebForms. But we were able to get around the problem by setting ClientIDMode="AutoID" for the control or page, we ended up setting our entire site that way cause we found problems that it happened to solve. Let me know if this works for you too. Wish I could be of greater help.
I would like to make a DropDownList inside a panel. This is my code from the codebehind file. But if I execute it, it always says: "in DropdownList it is not allowed to make multiple selections." Do I have to do something with the autopostback? So the error comes when I want to select something else than than "All".
DropDownList1.DataTextField = "Kanal";
DropDownList1.DataValueField = "Kanal";
DropDownList1.AppendDataBoundItems = true;
ListItem limDefault = new ListItem();
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
DropDownList1.Items.Add(limDefault);
Then this is my ASP.NET code:
<asp:Panel ID="Panel1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CR_SQL %>" SelectCommand="Select * from table" >
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="True">
</asp:DropDownList>
</asp:Panel>
I guess you execute the first snippet on every postback which adds the default item every time. Do that only at the first time the page loads, therefore use Page.IsPostBack to check that:
if(!IsPostBack)
{
ListItem limDefault = new ListItem();
limDefault.Selected = true;
limDefault.Text = "All";
limDefault.Value = "-1";
DropDownList1.Items.Add(limDefault);
}
i have grid view which have two drop down list. so user can change drop down list value at run time. here is my grid view design code :
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<asp:TemplateField HeaderText="Status" SortExpression="status_id">
<HeaderTemplate>
<asp:LinkButton ID="lbut_sortstatus1" runat="server"
CommandArgument="status_id" CommandName="Sort" CssClass="normaltext"
Font-Bold="true" Text="Status"></asp:LinkButton>
<asp:PlaceHolder ID="placeholderstatus1" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DDL_StatusList1" runat="server"
DataTextField="status_name" DataValueField="Id" AppendDataBoundItems="true"
AutoPostBack="True"
onselectedindexchanged="DDL_StatusList1_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="DDL_StatusList1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
<HeaderStyle CssClass="headinglist_bg" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
how ever this is my Page_Load code :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Status();
Bind_DDL_Group();
Bind_DDL_Countries();
}
this.GetData();
}
and here is my one of drop down list bind method that shows how i binding grid view drop down list.
public void Bind_DDL_Group()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Groups.Select(g=>g).OrderBy(g=>g.Group_name).ToList();
DataSet myDataset = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Group_name", typeof(string));
foreach (var item in query)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Group_name"] = item.Group_name.ToString();
dt.Rows.Add(dr);
}
myDataset.Tables.Add(dt);
DDL_GroupList.DataSource = myDataset;
DDL_GroupList.DataBind();
DropDownList bind_dropdownlist;
foreach (GridViewRow grdRow in GV_ViewUserList.Rows)
{
bind_dropdownlist = (DropDownList)(GV_ViewUserList.Rows[grdRow.RowIndex].Cells[8].FindControl("DDL_GroupList1"));
bind_dropdownlist.DataSource = myDataset;
bind_dropdownlist.DataBind();
}
}
}
however at Page load first time it's works successfully but when user clicks sorting or pagging then drop down list get empty. how ever i binds them in (!Page.IsPostBack) of Page_Load.
what I'm doing wrong here..
please help me...
Please put dropdown binding code out of if(!Page.IsPostBack) condition
Because when go to another page in gridview Page will be posted back to server
and if(!Page.IsPostBack) condition will return false.
Change your code to
if (!Page.IsPostBack)
{
Panel_View.Visible = false;
Session["SearchtText"] = null;
Session["ColumnName"] = null;
this.FillGrid((String)Session["ColumnName"] ?? null, (String)Session["SearchtText"] ?? null);
Bind_DDL_Column_List();
Bind_DDL_Title();
Bind_DDL_Countries();
}
Bind_DDL_Status();
Bind_DDL_Group();
this.GetData();
I a newbie to asp.net. I have created a DB table in sqlserver with 3 columns; ImageID, Filename & Score.
FileName is C:\pics\beads.png or C:\pics\moreimages\scenary.jpeg.
Using C# asp.net, I have created a GridView. This Gridview should populate
(column 1)ImageID and get the image from the Filename (column2) and I have 2 Checkboxlist created as shown below which should accept score for the images from user and save it into the DB table.
Question 1 .
I am able to populate Image ID, but Images are not getting populated.
Question 2.
I do not know how to access the checkboxlist since it is in template. The checked is in the default select and doesn't change even if I click on it. Which method/property should be used to do save the selection to the database. Here's my code
<form id="form1" runat="server">
<p style="height: 391px">
<asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" />
<asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:CheckBoxList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test">
<asp:ListItem Selected="True" Value="5">Good</asp:ListItem>
<asp:ListItem Value="0">Not Good </asp:ListItem>
<asp:ListItem Value="3">OK</asp:ListItem>
</asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" Width="130px" />
<asp:Button ID="Button2" runat="server" OnClientClick="javaScript:window.close(); return false;" Text="Exit" Width="102px" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</p>
</form>
public string sqlSel = #"SELECT TOP 3 [ImageID],FileName FROM [db1].[ImagesTest] where [Score] is null";
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand cmdSel = new SqlCommand(sqlSel, connection);
SqlDataReader reader1 = cmdSel.ExecuteReader();
while (reader1.Read())
{
DataSet ds = GetData(sqlSel);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Response.Write("Unable to connect to the database.");
}
}
}
}
private DataSet GetData(string cmdSel)
{
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter(cmdSel,con);
sda.Fill(ds);
}
catch (Exception ex)
{
Response.Write("IN EXCEPTION "+ex.Message);
return null;
}
return ds;
}
Thanks for ur time
Rashmi
There are several issues with your code, here is what it should be fixed:
How to fix the images (Question 1)
As #Guilherme said in the comments, for images use URLs instead of disk paths.
Replace the images disk paths C:\pics\beads.png or C:\pics\moreimages\scenary.jpeg to something like Images/beads.png and Images/scenary.jpeg.
For this to work, you will need to have a folder named Images that contains these two files on the same directory level as your .aspx file.
Adjust your GridView1 declaration in the ASPX file
On your GridView1 declaration you should:
attach a handler to the OnRowDataBound event. This will allow you to properly bind the Score dataset column to the Score gridview column
set the DataKeyNames property on the grid to what should be the primary key for your images table (in this case DataKeyNames="ImageID")
use a RadioButtonList instead of a CheckboxList, because according to your dataset you can only set one value, which is what the RadioButtonList does. The CheckboxList is normally used when multiple selection is needed.
attach a handler to the SelectedIndexChanged event on the RadioButtonList. This will allow you to save the new values to the database (Question 2)
Here's how your GridView declaration should look like:
<asp:GridView ID="GridView1" runat="server" Caption="Logos" Height="299px" Width="577px" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" DataKeyNames="ImageID">
<Columns>
<asp:BoundField DataField="ImageID" HeaderText="ImageID" />
<asp:ImageField DataImageUrlField="FileName" ControlStyle-Width="100"
ControlStyle-Height="100" HeaderText="Image" AlternateText="No image">
<ControlStyle Height="100px" Width="100px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="RadioButtonList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:RadioButtonList runat="server" AutoPostBack="true" RepeatColumns="3" ID="test" OnSelectedIndexChanged="test_SelectedIndexChanged">
<asp:ListItem Value="5">Good</asp:ListItem>
<asp:ListItem Value="0">Not Good </asp:ListItem>
<asp:ListItem Value="3">OK</asp:ListItem>
</asp:RadioButtonList>
<!-- UPDATED! - keep the old values in a hidden field -->
<asp:HiddenField runat="server" ID="hfOldScore" Value='<%# Eval("Score") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Adjust your code behind value in your .ASPX.CS file (Question 2)
On the code behind, you will also need to:
Make sure you are binding to the GridView only once in the Page_Load event, by checking the IsPostBack property
(Optional, but recommended) Move the logic of getting data (with the SQLConnection code) in a separate method that will handle only data retrieval
Implement the handler for the OnRowDataBound event. This will bind any values from the Score column to the RadioButtonList control
Implement the handler for the SelectedIndexChecked event of the RadioButtonList control. This will allow you to save to the database the new values
Finally, here's the entire code-behind code:
protected void Page_Load(object sender, EventArgs e)
{
//bind only the first time the page loads
if (!IsPostBack)
{
DataSet ds = GetData(sqlSel);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Response.Write("Unable to connect to the database.");
}
}
}
private DataSet GetData(string cmdSel)
{
//normally you should query the data from the DB
//I've manually constructed a DataSet for simplification purposes
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ImageID", typeof(int)));
dt.Columns.Add(new DataColumn("FileName", typeof(string)));
dt.Columns.Add(new DataColumn("Score", typeof(int)));
dt.Rows.Add(100, #"Images/beads.png", 0);
dt.Rows.Add(200, #"Images/moreimages/scenary.jpeg", 3);
dt.Rows.Add(300, #"Images/moreimages/scenary.jpeg", 5);
ds.Tables.Add(dt);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
//UPDATED - iterate through all the data rows and build a dictionary of items
//to be saved
Dictionary<int, int> dataToUpdate = new Dictionary<int, int>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
int imageID = (int)GridView1.DataKeys[row.RowIndex].Value;
int oldScore;
int newScore;
int.TryParse((row.FindControl("hfOldScore") as HiddenField).Value, out oldScore);
int.TryParse((row.FindControl("test") as RadioButtonList).SelectedValue, out newScore);
if (oldScore != newScore)
{
dataToUpdate.Add(imageID, newScore);
}
}
}
//update only the images that were changed
foreach (var keyValuePair in dataToUpdate)
{
SaveToDB(keyValuePair.Key, keyValuePair.Value);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//we are only interested in the data Rows
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow dataRow = (e.Row.DataItem as DataRowView).Row;
//manually bind the Score column to the RadioButtonlist
int? scoreId = dataRow["Score"] == DBNull.Value ? (int?)null : (int)dataRow["Score"];
if (scoreId.HasValue)
{
RadioButtonList test = e.Row.FindControl("test") as RadioButtonList;
test.ClearSelection();
test.SelectedValue = scoreId.Value.ToString();
}
}
}
protected void test_SelectedIndexChanged(object sender, EventArgs e)
{
RadioButtonList test = sender as RadioButtonList;
GridViewRow gridRow = test.NamingContainer as GridViewRow;
//obtain the current image Id
int imageId = (int)GridView1.DataKeys[gridRow.RowIndex].Value;
//obtain the current selection (we will take the first selected checkbox
int selectedValue = int.Parse(test.SelectedValue);
//UPDATED! - saves are now handled on the Save button click
//SaveToDB(imageId, selectedValue);
}
private void SaveToDB(int imageId, int score)
{
//UPDATED!
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.Parameters.Add("#ImageID", imageId);
command.Parameters.Add("#Score", score);
command.CommandText = #"update [db1].[ImagesTest] set Score = #Score where [ImageID] = #ImageID";
command.ExecuteNonQuery();
}
}
}
UPDATED!
The declaration of the GridView1 now contains a hidden field containing the Score value. You can use this hidden field to determine which row has changed, so you can trigger a save only on the changed ones
Save is now done on the click of the Save button, by iterating through the rows of the grid an building a Dictionary<int,string> to keep only the changes.
SaveToDB method should work, but I cannot test this myself.
Question 2:
To access your checkbox you can use.
GridViewRow row = GridView1.Rows[i];
CheckBox Ckbox = (CheckBox)row.FindControl("test");
For Question 1
Instead of ImageField you can use use ASP:Image in Templatefield like this
<asp:TemplateField HeaderText="Score" AccessibleHeaderText="CheckBoxList" ValidateRequestMode="Enabled">
<ItemTemplate>
<asp:Image ID="imageControl" runat="server" ImageUrl='<%# Eval("Filename") %>'></asp:Image>
</ItemTemplate>
</asp:TemplateField>
For Question 2
This is one of the example for how to access each Checkbox list inside gridview
For Each gvr As GridViewRow In Gridview1.Rows
If (CType(gvr.FindControl("CheckBox1"), CheckBox)).Checked = True Then
ReDim uPrimaryid(iCount)
uPrimaryid(iCount) = New Integer
uPrimaryid(iCount) = gvr.Cells("uPrimaryID").Text
iCount += 1
End If
Next