Drop-down Selected Value not Showing in my Detailview - c#

I have drop-down that is not showing the previoiusly selected value in my Detailview. It always shows me the first value in the list. If the previously selected value was xyz then when the Detailvies loads, i want to show xyz. I have researched a lot but could not find any solution that i can use. please help
here is my aspx code for the field that has the dropdown
<asp:TemplateField HeaderText="Name:">
<ItemTemplate>
<asp:Label ID="lbl_UID" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddl_Name" Width="200px" Height="25" DataSourceID="SDS_Manager" DataTextField="FULL_NM" AutoPostBack="false"
DataValueField="UID" runat="server" AppendDataBoundItems="false">
<asp:ListItem Text="Select Name" Value="Select Name"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
here is the code behind that binds the detailview
protected void Edit(object sender, EventArgs e)
{
using (GridViewRow row = (GridViewRow)((LinkButton)sender).Parent.Parent)
{
sqlcon.Open();
sqlcmd = new SqlCommand(#"Select PRJ_ID, WPC_CD, WPC_DESC, Name FROM myTable where PRJ_ID = '" + myvar + "' ", sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
DV_Edit.DataSource = dt;
DV_Edit.DataBind();
sqlcon.Close();
popup.Show();
}
}

Try setting AutoPostBack="true" and make sure if you have any logic to set the value of the drop down in the page load, that the code is not executed on post back as shown below.
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
ddlOne.DataSource = //your data here;
ddlOne.DataBind();
}
}
//if you don't wrap this logic in the if(!IsPostBack), the code will simply re-populate
//the drop down and set the selected index to the first item in the list with each
//post back.

Related

gridview findcontrol returning nothing empty string(Blank)

I am trying to pass a session value from a gridview select row using GridView1_RowEditing1 event. i am able to get session value for primarykey (p.key) but the Associate_ID returns empty.
C# Code behind
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
int primarykey = Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);
string name = Convert.ToString(GridView1.Rows[e.NewEditIndex].FindControl("Associate_ID"));
Session["Number"] = primarykey;
Session["Name"] = name;
//redirect
Response.Redirect("updatee.aspx");
}
.ASPX
<asp:TemplateField HeaderText="Associate_ID" SortExpression="Associate_ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
OUTPUT:
Key: 5
Name:
As you can see i am not getting Associate_ID for selected field.
Also tried using
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("Associate_ID"));
but there was no result, the grid has multiple columns and rows (8*15)
tried suggestions on gridview findcontrol returning empty "" and tried stopping re-binding the GridView on the PostBack.
removed DataSourceID from gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//DataSourceID = "SqlDataSource1"
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
None of this helped. I am still getting a blank value for Associate_ID.
i am unable to see where the issue is. Please help!
You are trying to find the Control Associate_ID with FindControl. But it does not exist. Either find TextBox1 or rename the TextBox to Associate_ID.
<EditItemTemplate>
<asp:TextBox ID="Associate_ID" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
//or
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("TextBox1"));
UPDATE
I see the problem, somehow you are trying to access those control before the edit state has been activated by rebinding the GridView. The edit index has not been set. So place this before the FindControl.
GridView1.DataSource = yourSource;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
Thank you so much VDWWD, i was finally able to get it to work.
The problem was i was not able to use get my 'TextBox' element in gridview using FindControl.
The solution was to not re-binding the GridView on the PostBack of the page and edit index on the RowEditing event.
This is what my working code looks like, is any one ever comes across a similar issue
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txt = GridView1.Rows[e.NewEditIndex].FindControl("TextBox1") as TextBox;
string name = txt.Text;
}
.ASPX
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>
</EditItemTemplate>

Add items in Cart, and displaying them in a drop down list

I am programming in visual studio.
I have a dropdown list where user is able to choose among different products, and price to the corresponding products appears in a label in front of it.
I have a button name add to cart, and a dropdown list under it.
What I want is: as soon as a product is chosen in the first drop down list, after clicking add to cart, that product should also come in the second dropdown list (in my case: Items in cart). As many as products are chosen, it should come to the drop down list; pretty much like a real life Add to cart option.
And also a calculated price for all the products stored in the cart will be displayed in a label that I have created.
[Please ask me if you need any clarification about my question].
Store.aspx:
<form id="form1" runat="server">
<div>
Select Products: <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="GetPrice" AutoPostBack="True">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [productdata]"></asp:SqlDataSource>
Price:
<asp:Label ID="Label1" runat="server" ></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Add to Cart" OnClick="Button1_Click" />
<br />
Items in cart: <asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
<br />
Total Price: <asp:Label ID="Label2" runat="server"></asp:Label>
</div>
</form>
Store.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label3.Text = Request.QueryString["name"];//show welcome text
String cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection sc = new SqlConnection(cs))
{
SqlCommand sqlcom = new SqlCommand("Select id, productname, price from productdata", sc);
sc.Open();
//DropDownList1.Items.Add(new ListItem("0", "select one"));
DropDownList1.DataTextField = "productname";//show in the dropdown list
DropDownList1.DataValueField = "price"; //show in the label
DropDownList1.DataSource = sqlcom.ExecuteReader();
//DropDownList1.Items.Insert("0", new ListItem("choose value"));
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("select one", "0"));
}
}
}
protected void GetPrice(object sender, EventArgs e)
{
Label1.Text = DropDownList1.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
//add to the cart
}
On Button1_Click you should do two easy things:
You need to take the selected item from the first DropDownList and add it to the Cart's DropDownList, using DropDownList2.Items.Add(selectedItem);
To show the total price you need to sum up all the DropDownList items using:
DropDownList2.Items.Cast().Select(a => Convert.ToInt32(a.Value)).Sum();
You can definitely read more about summing up DropDownList items in a previous SO post:
How to sum all values of a dropdown list
In Conclusion
This should work for you:
protected void Button1_Click(object sender, EventArgs e)
{
// Get the selected item
ListItem item = DropDownList1.SelectedItem;
// Reset selected to false
item.Selected = false;
// Add to the cart dropdown
DropDownList2.DataTextField = "productname";
DropDownList2.DataValueField = "price";
DropDownList2.Items.Add(item);
DropDownList2.DataBind();
int sum = DropDownList2.Items.Cast<ListItem>().Select(a => Convert.ToInt32(a.Value)).Sum();
Label2.Text = Convert.ToString(sum);
}
Hope it helps! If you have any more questions I will be happy to help

Asp.Net C# Delete row from dataTable gridview on button click

I'm displaying a datatable that selects a number of elements from the database (IncomingsId, Type, Cost, Frequency) and I'm not sure how to delete a row when a button is clicked.
I've tried many solutions so far but nothing is working.
Here is the button I have within my Grid view
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:button id="DeleteRowButton" text="Delete Record" onclick="DeleteRowButton_Click" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
And here is the code behind this page were I am creating the datatable.
SqlConnection con;
public _Default()
{
con = new SqlConnection(#"MySQLConnection");
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisplayRecord();
}
}
public DataTable DisplayRecord()
{
string userId = (HttpContext.Current.User.Identity.GetUserId());
SqlDataAdapter Adp = new SqlDataAdapter("select * from Incomings where AspNetUsersId = '" + userId +"'", con);
DataTable Dt = new DataTable();
Dt.AcceptChanges();
Adp.Fill(Dt);
grid1.DataSource = Dt;
grid1.DataBind();
return Dt;
}
public void DeleteRowButton_Click(object sender, EventArgs e)
{
}
Cheers in advance for any help. I'm sure it's a simple resolution
You need a way for your code to know which ID to delete. Here is how I would normally do it:
Replace your button with an ItemTemplate, and add the button in here instead:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument='<%# Eval("userId") %>' CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
When you have the button this way, you now have access to a CommandArgument and CommandName attributes. Notice the argument I am passing is Eval("userId"), the command name (as you will see later) is used to recognize what action you want to execute (this could be anything, is just a name).
Replace the CommandArgument with whatever value(s) you want to pass to the server, using the name that came from the database/datasource (I am guessing it would be userId).
Then, to capture this you need to implement the RowCommand event of the GridView, and intercept the correct CommandName:
public void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string userId = e.CommandArgument.ToString();
//do something with the id
}
}
Here you have to make sure the CommandName in your button, matches to whatever action you want to execute in the RowCommand. This should do the trick.
Don't forget to bind the event to your GridView:
<asp:GridView OnRowCommand="GridView1_RowCommand" ID="GridView1" runat="server">
...
</asp:GridView>
just use this for the front-end code
<asp:GridView ID="grid1" OnRowDeleting="OnRowDeleting" DataKeyNames="deleteR" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" style="width:100%" >
<columns>
<asp:TemplateField HeaderText="Delete Row">
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" class="btn btn-primary" Text="Delete" CommandName="Delete" OnRowDataBound="OnRowDataBound" />
</ItemTemplate>
</asp:TemplateField>
And have this in behind it:
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int deleteR= Convert.ToInt32(grid1.DataKeys[e.RowIndex].Values[0]);
//have a sql statement here that add's the parameter ID for the row you want to delete, something like
SqlCommand com = new SqlCommand ("Delete FROM yourdatabase Where yourID = #yourID"
com.Parameters.AddWithValue("#yourID", yourID)
}
What you're looking for is indeed a simple solution.
You can use a foreach loop to search all DataRows within the DataTable for some kind of ID.Here's an example of what I mean:
String s = "/* IncomingsId for what you want to delete */";
foreach (DataRow r in dt.Rows) {
if (r["IncomingsId"].ToString().Equals(s)) {
dt.Rows.Remove(r);
}
}
Just a quick update for anyone that's helped me, thanks for your advice.
Asp.Net has it's own built in AutoGenerateDeleteButton and I set that to true and ran a bit of code behind it.
A simple solution that really shouldn't have taken me all day to complete!

Listview Update not workng

I'm trying to change the Select Command my DataSource uses using a dropdownlist. When the page loads it sets the select command depending on the selected index. When I change the dropdownlist the page refreshes but the data doesn't! Where am I going wrong?
.aspx file
<asp:DropDownList ID="filmFilter" runat="server" OnSelectedIndexChanged="filmFilter_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem Value="">Filter</asp:ListItem>
<asp:ListItem Value="priceASC">Price: Low-High</asp:ListItem>
<asp:ListItem Value="priceDSC">Price: High-Low</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringFilms %>"></asp:SqlDataSource>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="filmID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
...
</ItemTemplate>
<LayoutTemplate>
...
</LayoutTemplate>
</asp:ListView>
code-behind - page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (filmFilter.SelectedIndex == 0)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films]";
}
if (filmFilter.SelectedIndex == 1)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice]";
}
if (filmFilter.SelectedIndex == 2)
{
SqlDataSource1.SelectCommand = "SELECT * FROM [films] ORDER BY [filmPrice] DESC";
}
}
}
Thanks!
You've got it so your datasource is set on the page_load which is fine but you've wrapped it in
if (!IsPostBack)
{
Which means your code to change the datasource will only happen when you are not in postback (when you change the value of the dropdown you will be in a postback)
Have a read through
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
It will help with your understanding

ASP.NET c# Checkboxlist in a template field

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

Categories