I have two SqlDataSources that relate to two dropdownlists. The PopulateDLL() method allows me to populate the first dropdownlist with towns and filters the second dropdownlist with street names related to that town, however some street names also have building names (i.e. City Hall, Main Street), what I'm trying to do is include the building name with the appropriate street names. I researched this and got the code
dt.Columns.Add("StreetName + BuildingName");
ddl_FilteredLocation.DataTextField = "BuildingName";
//ddl_FilteredLocation.DataValueField = "";
ddl_FilteredLocation.DataBind();
However it still only calls the street name, I've tried different variations and sometimes only the building name will appear but no street name, any help with this would be great, thanks!
<%-- DS for DDL Location --%>
<asp:SqlDataSource ID="ds_Location" EnableCaching="false" DataSourceMode="DataSet" runat="server" >
ConnectionString="<%$ ConnectionStrings:DataTown %>"
SelectCommand="SELECT DISTINCT Town FROM [DataTown].[dbo].[DT] Order By Town">
<asp:SqlDataSource>
<%-- DS for DDL Street Name, filterExpression is used so that when a user selects a town from ddl_Location the streets for that town are filtered --%>
<asp:SqlDataSource ID="ds_StreetName" EnableCaching="true" DataSourceMode="DataSet" runat="server" ConnectionString="<%$ ConnectionStrings:DataTown %>"
SelectCommand="SELECT Town, BuildingName, StreetName FROM [DataTown].[dbo].[DT] Order By StreetName" FilterExpression="Town = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="Town" ControlID="fmv_AccidentHSUData$ddl_Location" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="ddl_Location" AutoPostBack="true" Width="100%" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddl_FilteredLocation" DataSourceID="ds_StreetName" DataTextField="StreetName" DataValueField="StreetName" AutoPostBack="true" Width="100%" runat="server">
protected void PopulateDDL()
{
DropDownList ddl_Location = (DropDownList)fmv_DataTown.FindControl("ddl_Location");
DropDownList ddl_FilteredLocation = (DropDownList)fmv_DataTown.FindControl("ddl_FilteredLocation");
ddl_Location.Items.Clear();
DataView view = (DataView)ds_Location.Select(DataSourceSelectArguments.Empty);
DataTable dt = view.ToTable();
dt.Columns.Add("StreetName + BuildingName");
ddl_FilteredLocation.DataTextField = "BuildingName";
//ddl_FilteredLocation.DataValueField = "";
ddl_FilteredLocation.DataBind();
foreach (DataRow row in dt.Rows)
{
string Town = row["Town"].ToString();
//string StreetName = row["StreetName"].ToString();
string FullText = "";
if (Town.Length > 0)
{
FullText = Town;
}
else
{
}
ddl_Location.Items.Add(new ListItem(FullText, FullText));
}
}
The code underneath is the solution to the problem I had
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateDDL();
}
}
protected void PopulateDDL()
{
DropDownList ddl_Location = (DropDownList)fmv_DataTown.FindControl("ddl_Location");
DropDownList ddl_FilteredLocation = (DropDownList)fmv_DataTown.FindControl("ddl_FilteredLocation");
ddl_Location.Items.Clear();
DataView view = (DataView)ds_Location.Select(DataSourceSelectArguments.Empty);
DataTable dt = view.ToTable();
foreach (DataRow row in dt.Rows)
{
string Town = row["Town"].ToString();
string FullText = "";
if (Town.Length > 0)
{
FullText = Town;
}
else
{
}
ddl_Location.Items.Add(new ListItem(FullText, FullText));
}
}
Related
I want display student information and student image on my web page while selecting student Id from drop down list. Given below code is used for displaying information and image. But the image is not showing properly. Please check the code and out put screen.
Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"].ToString());
TextBox2.Text = (row["SecondName"].ToString());
byte[] barrImg = (byte[])row["StudImage"];
string base6=Convert.ToBase64String(barrImg);
Image1.ImageUrl = "data:image/jpeg;base6," + base6;
}
}
SQL Query:
SELECT FirstName, SecondName, StudentImage FROM TextBoxTable WHERE (Id = #Id)
Aspx Source:
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Image ID="Image1" runat="server" />
</div>
Data base:
OutPut:
base64 instead of base6 ???
Image1.ImageUrl = "data:image/jpeg;base64," + base6;
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
Inside gridview a dropdownlist is there
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:DropDownList ID="quantity" runat="server" DataValueField="ItemID" DataTextField="Quantity">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
for each itemid there is some numeric value in Quantity field of Database Table
i want that this dropdown must contain the values from 1 to quantity.DataTextField for all the items present in the cart
the procedure by which gridview is bound is
create proc [dbo].[prcItemsinCart](#CartID int)
as
select distinct ct.Price,ct.Quantity,ct.ItemID,
ct.CartID,ct.ProductID,p.ProductName,
isnull(( select top 1 convert(varchar,PhotoID,10) + '.' + ExtName
from ProductPhoto
where ProductID = ct.ProductID ),'NoImage.jpg'
) as Product,
( Select Price*Quantity
from CartItems
where CartID=ct.CartID and ProductID=ct.ProductID
) as SubTotal
from CartItems as ct
inner join ProductInfo as p on ct.ProductID=p.ProductID
inner join ProductPhoto as pp on ct.ProductID=pp.ProductID
where ct.CartID=#CartID
I would add a HiddenField in the TemplateField to hold the CartID, I will use the CartID in the code. My Markup should look like:
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:HiddenField ID="hdnId" runat="server" value='<%#Eval("CartID") %>'></asp:HiddenField>
<asp:DropDownList ID="quantity" runat="server" DataValueField="ItemID" DataTextField="Quantity">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
In the code, in GridView's RowDataBound I am finding the DropDownList and HiddenField, running a Sql Query to bring my expected data, and binding them to my DropdownList:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList quantity = e.Row.FindControl("quantity") as DropDownList;
HiddenField hdnId = e.Row.FindControl("hdnId") as HiddenField;
if (quantity != null && hdnId != null)
{
string queryString = String.Format("SELECT ItemID, Quantity FROM CartItems WHERE CartID= {0}", hdnId.Value);
//MyConnectionString is your connection string in web.config
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
quantity.DataSource = reader;
quantity.DataValueField = "ItemID";
quantity.DataTextField = "Quantity";
quantity.DataBind();
}
}
}
}
Gridview contains 100 customer, each page 10 customer, how to filter Alphabatically;
If an user clicks A, then list out all customer names that starts with A
Please help.
If you're using an SqlDataSource, you can specify a parameter in the SelectCommand, e.g.
SelectCommand="SELECT * FROM [Genre] WHERE [Name] LIKE #FirstLetter+'%'"
You will have to add the parameter within the , e.g.
<SelectParameters>
<asp:Parameter Name="FirstLetter" Type="String" />
</SelectParameters>
In your code behind, you can set the value of the parameter, e.g.
SqlDataSource1.SelectParameters["FirstLetter"].DefaultValue = filterletter;
The Faster and jQuery Approach is mentioned in this link
$(document).ready(function() {
$('#<%=lblNoRecords.ClientID%>').css('display','none');
$('.links').click(function(e)
{
$('#<%=lblNoRecords.ClientID%>').css('display','none');
var lnkText = $(this).text().toLowerCase();
var iCounter = 0;
$("#<%=gdRows.ClientID%> tr:has(td)").each(function() {
var cell = $(this).find("td:eq(1)").text().toLowerCase();
if(lnkText != 'all')
{
if(cell.indexOf(lnkText) != 0)
{
$(this).css('display','none');
}
else
{
$(this).css('display','');
iCounter++;
}
}
else
{
$(this).css('display','');
iCounter++;
}
});
if(iCounter == 0)
{
$('#<%=lblNoRecords.ClientID%>').css('display','');
}
e.preventDefault();
});
});
Approach #1
ASPX markup:
<asp:Repeater ID="rptAlpha" runat="server" OnItemCommand="rptAlpha_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lbAlpha" runat="server"
CommandArgument='<%# Container.DataItem.ToString() %>'><%#Container.DataItem.ToString() %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1">
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
OldValuesParameterFormatString="original_{0}"
OnSelecting="ObjectDataSource1_Selecting" SelectMethod="Load" TypeName="Your.TypeName.Here">
<SelectParameters>
<asp:Parameter Name="Filter" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
BindAlphaRepeater();
}
private void BindAlphaRepeater()
{
string[] alphabet = {"a", "b", "c", "d", "e" };
rptAlpha.DataSource = alphabet;
rptAlpha.DataBind();
}
protected void rptAlpha_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string filterleter = e.CommandArgument as string;
if (filterleter == null)
return;
ViewState["filterletter"] = filterleter;
GridView1.DataBind();
}
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
// This is designed to return null, you might want to change it to a default value
e.InputParameters["Filter"] = ViewState["filterletter"] as string
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Paging click");
GridView1.DataBind();
}
Explanation:
User a repeater to bind the alphabets and use OnItemCommand of that Repeatet to fetch data and bind the grid view based on selected alphabet.
Approach #2
You can have 26 buttons on top of gridview + one button for All on top of the gridview.
For all 26 buttons you can have common method like buttonAPLHA_Click and based on sender.tag you can filter the data of the gridview.
e.g inside your buttonAPLHA_Click you can have.
GridView.datasource = GetDataByAplha(Sender.Tag.Tostring());
Hope you get what I want to explain.
use this sample query..
string query = "select from tbl_name where name like '%" + dropdownlist.SelectedValue + "'";
I have placed a checkboxlist in a formview object.
I would like to store and load the results of the checkboxlist in a table of an entity framework.
I filled the cbl with values and labels coming from a table that has 2 columns, using the DataSourceID, DataTextField and DataValueField attributes but I can't seem to find how to bind the cbl to the entity framework object in order to store the checked values when the formview is in "EDIT" mode.
Any help would be appreciate. Thanks!
<asp:FormView ID="formView1" runat="server" DataSourceID="Ods1"
Height="203px" Width="495px"
onpageindexchanging="formView1_PageIndexChanging">
<EditItemTemplate>
<asp:CheckBoxList ID="cblProducts" runat="server" RepeatColumns="3"
Width="782px" DataSourceID="SqlDataSource1" DataTextField="ProductName"
DataValueField="ProductCode">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [ProductCode], [ProductName] FROM [Products]">
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
<asp:ObjectDataSource ID="Ods1" runat="server"
DataObjectTypeName="WebApplication1.EDM.Emp" DeleteMethod="DeleteEmp"
InsertMethod="CreateNewEmp" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetEmpByEmpId" TypeName="WebApplication1.EDM.EmpLogic"
UpdateMethod="UpdateEmp" OnSelecting="Ods1_Selecting">
<SelectParameters>
<asp:RouteParameter Name="EmpId" RouteKey="EmpId" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:FormView ID="formView1" runat="server"
OnItemUpdating="formView1_ItemUpdating" ...>
protected void formView1_ItemUpdating(object sender, FormViewUpdateEventArgs e)
{
var cblProducts = formView1.FindControl("cblProducts") as CheckBoxList;
foreach (ListItem item in cblProducts.Items)
{
if (item.Selected)
{
// Check if item.Value is not in the db for this employee, if so add it
}
else
{
// Check if item.Value is in the db for this employee, if so delete it
}
}
// save
}
You need to do the following;
foreach (ListItem chk in cblProducts.Items)
{
string productId= chk.Value;
if (IsProductAvailable(productId) // this method will basically goes to database and return true of false
chk.Selected = true;
else
chk.Selected = false;
}
private void IsProductAvailable(string productId)
{
string query = "SELECT [ProductId] FROM [Product] ";
query += "WHERE [ProductId] = #ProductId";
DbCommand comm = new DbCommand();
comm.CommandText = query;
DbParameter param = comm.CreateParameter();
param.ParameterName = "#ProductId";
param.Value = productId;
comm.Parameters.Add(param);
DataTable table = comm.ExecuteCommand();
if (table.Rows.Count > 0)
{
return true;
}
else
return false;
}
please modify query and parameters according to your need.