How to highlight search results in gridview using asp.net? - c#

I am using a search box to sort my gridview according to the search text. I want to highlight the matching text in the gridview entered into the textbox.
This is my aspx page-
<table>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server" Width="167px">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Submit" Width="116px" />
</td>
</tr>
<tr>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</tr>
</table>
code behind
public void bind()
{
dt = g1.return_dt("select * from tbl1 where id is not null "
+ Session["Name"] + " order by compname ");
if (dt.Rows.Count > 0)
{
adsource = new PagedDataSource();
adsource.DataSource = dt.DefaultView;
adsource.PageSize = 10;
adsource.AllowPaging = true;
adsource.CurrentPageIndex = pos;
btnfirst.Enabled = !adsource.IsFirstPage;
btnprevious.Enabled = !adsource.IsFirstPage;
btnlast.Enabled = !adsource.IsLastPage;
btnnext.Enabled = !adsource.IsLastPage;
GridView1.DataSource = adsource;
GridView1.DataBind();
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
Session["Name"] = string.Format("and compname like '%{0}%' or productcategory like '%{0}%' or country like '%{0}%'");
}
else
{
Session["Name"] = null;
}
}
Please guide me how can I do this.

You can do it in two ways:
Modify the text in the relevant columns of you data table. (Find the text in each column and add an span with css class surrounding that text.) Here is a sample:
foreach(DataRow dr in dt.Rows)
{
foreach(DataColumn dc in dt.Columns)
{
string s = Convert.ToString(dr[dc.ColumnName]);
s = s.Replace("Your Search Text","<span style='color:RED'>Your Search Text</span>");
dr[dc.ColumnName] = s;
}
}
You can use javascript for the same and let the browser do all the hardwork. (Refer this link for a sample.)
Hope this helps.

Related

foreach by check on two control (dropdownlist and textbox)

I have issue on doing the foreach part, I have multiple dropdownlist attach together with a textbox for filling quantity
But with my current code it will have issue with running all value in the foreach textbox first just until the next foreach of dropdownlist. Below is my code of now.
foreach (DropDownList dropDown in pnlDDLDispensary.Controls.OfType<DropDownList>()){foreach (TextBox textBox in pnltxtDispensaryQty.Controls.OfType<TextBox>()){ code here }}
My objective is want to insert each of the dropdownlist dispensary together with the quantity of that dispensary like example: (MedicineA with 5 quantity, MedicineB with 1 quantity). Is there anything like foreach( a in control && b in control)? Appreciate for help. Thanks~
protected void cmdDelete_ServerClick(object sender, EventArgs e)
{
GridToTable(); //This function havent done due to also having DataKeys cannot used like a method error
Button btnDelete = (Button)sender;
ListViewItem gRow = (ListViewItem)btnDelete.NamingContainer;
int disID = lvDispensary.DataKeys(gRow.DataItemIndex).Item("dispensaryID");
}
Result:
CS1955: Non-invocable member 'ListView.DataKeys' cannot be used like a method.
It not at all clear what kind of "system" or choice you have made to show the repeating drop down and text box.
As a general rule, if you need to "repeat" controls, then you use a listview, repeater, or even maybe a grid view.
so it will not matter if you have 1 or 15 row of repeating data (you don't care how many).
So, I might say have 1 or 8 hotels, and I have a combo box to rate the hotel.
So, hum, lets use the repeater.
So, we only need to drop/have one instance of the markup layout.
Say, like this:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblH" runat="server" Text="Hotel Name" Font-Size="Medium">
</asp:Label>
<asp:TextBox ID="txtHotel" runat="server"
Text = '<%# Eval("HotelName") %>'
style="margin-left:20px" >
</asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server"
style="margin-left:20px;width:120px"
DataValueField = "ID"
DataTextField = "Rating" >
</asp:DropDownList>
<br />
</ItemTemplate>
</asp:Repeater>
and our code behind is this:
DataTable rstRating = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
// set combo box source
rstRating =
MyRst("SELECT ID, Rating FROM tblRating ORDER BY ID");
DataTable rstData =
MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
Repeater1.DataSource = rstData;
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item |
e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList dl = (DropDownList)e.Item.FindControl("DropDownList1");
dl.DataSource = rstRating;
dl.DataBind();
dl.Items.Insert(0, new ListItem("Please Select", "0"));
}
}
and now we get this:
so, above works for 2 or 20 rows of data. We don't care how many rows.
but, now to do a for each on the repeating controls?
This:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem OneRow in Repeater1.Items)
{
TextBox txtHotel = (TextBox)OneRow.FindControl("txtHotel");
DropDownList cboRate = (DropDownList)OneRow.FindControl("DropDownList1");
Debug.Print("Hotel name = " + txtHotel.Text + " -- Rating = " +
cboRate.SelectedItem.Text);
}
}
And output is this:
So, for a "set" or "thing" of repeating data, then use some type of control such as a repeater.
I mean, for above, we could also use a listview, and that also is quite nice, say like this:
<div style="width:24%">
<asp:ListView ID="LVHotels" runat="server" DataKeyNames="ID" OnItemDataBound="LVHotels_ItemDataBound" >
<ItemTemplate>
<tr style="">
<td>
<asp:TextBox ID="txtHotel" runat="server"
Text = '<%# Eval("HotelName") %>'
style="margin-left:20px" >
</asp:TextBox>
</td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
style="margin-left:20px;width:120px"
DataValueField = "ID"
DataTextField = "Rating" >
</asp:DropDownList>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" class="table table-bordered">
<tr runat="server" style="">
<th runat="server">Hotel Name</th>
<th runat="server">Rating</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
</div>
Same code to bind, and we now have this:
And then once again, our for each code against that listview is much the same.
So, the idea here?
If you have repeating controls, then use some type of gridview, repeater, or listview.
that way, its all data driven, and once done, then 2 or 20 rows - it don't matter, and you can use for each against these containers that repeated the data for you.
Edit: User wants a List View example.
Ok, so markup for this is this:
<div style="width:30%">
<style>
.borderhide input {border:none;background-color:transparent}
.borderhide textarea {border:none;background-color:transparent}
</style>
<asp:ListView ID="LVHotels" runat="server" DataKeyNames="ID" OnItemDataBound="LVHotels_ItemDataBound" >
<ItemTemplate>
<tr style="">
<td><asp:TextBox ID="txtFirst" runat="server" Text='<%# Eval("FirstName") %>' width="80px"></asp:TextBox></td>
<td><asp:TextBox ID="txtLast" runat="server" Text='<%# Eval("LastName") %>' width="80px"></asp:TextBox></td>
<td><asp:TextBox ID="txtHotel" runat="server" Text='<%# Eval("HotelName") %>' width="110px"></asp:TextBox></td>
<td>
<asp:DropDownList ID="DropDownList1" runat="server"
style="width:120px"
DataValueField = "ID"
DataTextField = "Rating" >
</asp:DropDownList>
</td>
<td>
<button id="cmdDelete" runat="server" class="btn"
onserverclick="cmdDelete_ServerClick"
onclick="if (!confirm('Really delete')) {return false}" >
<span aria-hidden="true" class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" class="table table-bordered borderhide">
<tr runat="server" style="">
<th runat="server">First Name</th>
<th runat="server">Last Name</th>
<th runat="server">Hotel Name</th>
<th runat="server">Rating</th>
<th runat="server"></th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
<tfoot><tr><td>
<button id="cmdAddNew" runat="server" class="btn" onserverclick="cmdAddNew_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-plus-sign"> New</span>
</button>
</td></tr></tfoot>
</table>
</LayoutTemplate>
</asp:ListView>
</div>
<br />
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-floppy-saved"> Save</span>
</button>
<button id="cmdCancel" runat="server" class="btn" style="margin-left:15px" onserverclick="cmdCancel_ServerClick">
<span aria-hidden="true" class="glyphicon glyphicon-arrow-left"> Back/Cancel</span>
</button>
</div>
And our full code for this is this:
DataTable rstRating = new DataTable();
DataTable rstData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
Session["rstData"] = rstData;
Session["rstRating"] = rstRating;
}
else
{
rstData = (DataTable)Session["rstData"];
rstRating = (DataTable)Session["rstRating"];
}
}
void LoadData()
{
// set combo box source
rstRating = MyRst("SELECT ID, Rating FROM tblRating ORDER BY ID");
rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
LVHotels.DataSource = rstData;
LVHotels.DataBind();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void LVHotels_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DropDownList dl = (DropDownList)e.Item.FindControl("DropDownList1");
dl.DataSource = rstRating;
dl.DataBind();
dl.Items.Insert(0, new ListItem("Please Select", "0"));
// now set to current data row
DataRowView OneRow = (DataRowView)e.Item.DataItem;
if (OneRow["Rating"] != null)
dl.SelectedValue = OneRow["Rating"].ToString();
}
}
protected void cmdSave_ServerClick(object sender, EventArgs e)
{
SaveAllData();
// data saved - move on to next page
// Response.Redirect("MyMain.aspx");
}
protected void cmdAddNew_ServerClick(object sender, EventArgs e)
{
DataRow NewRow = rstData.NewRow();
rstData.Rows.Add(NewRow);
// show this row
LVHotels.DataSource = rstData;
LVHotels.DataBind();
}
void SaveAllData()
{
GridToTable(); // move grid back to table
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = 0", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
// rstData.AcceptChanges()
}
}
}
protected void cmdCancel_ServerClick(object sender, EventArgs e)
{
// cancel without save - go back some place to other page
// Response.Redirect("MyMain.aspx");
}
void GridToTable()
{
// send LV rows back to our table.
foreach (ListViewItem rRow in LVHotels.Items)
{
int RecordPtr = rRow.DataItemIndex;
DataRow OneDataRow = rstData.Rows[RecordPtr];
OneDataRow["FirstName"] = ((TextBox)rRow.FindControl("txtFirst")).Text;
OneDataRow["LastName"] = ((TextBox)rRow.FindControl("txtLast")).Text;
OneDataRow["HotelName"] = ((TextBox)rRow.FindControl("txtHotel")).Text;
DropDownList dlRating = (DropDownList)rRow.FindControl("DropDownList1");
if (dlRating.SelectedIndex == 0)
OneDataRow["Rating"] = null;
else
OneDataRow["Rating"] = dlRating.SelectedItem.Value;
}
}
protected void cmdDelete_ServerClick(object sender, EventArgs e)
{
// we actully should saveAllData before we do this
// we might have added rows without save and thus
// pk not correctly valid
// so we need to actaully check deleted row status here.
HtmlButton btn = (HtmlButton)sender;
ListViewItem gRow = (ListViewItem)btn.NamingContainer;
int RowIndex = gRow.DataItemIndex;
int PK = (int)LVHotels.DataKeys[RowIndex]["ID"];
string strSQL = "DELETE FROM tblHotelsA WHERE ID = " + PK;
Debug.Print("will delete - future code");
}
And we now have get this:
So, you can:
Tab around - edit + change any row - including combo box
Add new rows
THEN hit save button, all edits, adding, edits and even delete(s) will now go back to sql server table.
The data bound event for the listview in above is what you are looking for.
Only part left out is delete button - but that should be easy.
Edit3: adding the delete button code
As noted, if we are to allow delete, then we STILL have to hit the save button, and the un-do changes button WILL still work!!! So, the user can add a few rows, delete a few rows - and then go "opps" wrong rows deleted. Since we not yet hit save, then we not actaully deleted the data. (and this means our un-do button can still work).
But, what this means? well in rstData, then rows of DELETED data WILL exist. We can feed rstData to the LV, and such rows don't show.
But, using for/each on the rstData? Then YES DELETED rows will show up!
And if the LV displays 5 rows, but we had 10 and deleted 5 of them?
Then as noted, we NOW cannot USE the LV "index" to peek into rstData anymore. But, we can still use Datakeys. BEYOND critial then that you set datakeys setting in the LV markup as I have done above.
So, first up, the delete button code. User might bounce around, edit some rows, maybe add. But then hits delete button.
So, this code is easy. (also note the JavaScript confirm prompt to confirm the delete button).
hence this:
Protected Sub cmdDelete_ServerClick(sender As Object, e As EventArgs)
' save any edits BACK to table before delete
' this ONLY delets from persited table - not SQL server.
GridToTable()
Dim btn As HtmlButton = sender
Dim gRow As ListViewItem = btn.NamingContainer
Dim PK As Integer = ListView1.DataKeys(gRow.DataItemIndex).Item("ID")
Dim OneDataRow As DataRow = rstData.Select("id = " & PK)(0)
OneDataRow.Delete()
DisplayUpdate()
End Sub
Note VERY close in above. We did not (and can't) use the LV index into our table, since rstData now can have more rows then the LV display. (LV is smart, only display rows that are not deleted).
So, in above, we dumped "index" from LV into rstData, and we now use PK value.
This also now means our GridToTable can't use the simple "index" into rstdata, and we MUST pull each row from rstData by PK value (we have to search/find the PK row based on PK).
So, GridToTable now has to be this:
Sub GridToTable()
' send grid rows back to persited table
For Each gRow As ListViewItem In ListView1.Items
' Get database PK value
Dim PK As Integer = ListView1.DataKeys(gRow.DataItemIndex).Item("ID")
Dim drT() As DataRow = rstData.Select("ID = " & PK, "", DataViewRowState.CurrentRows)
If drT.Length > 0 Then
Dim OneDataRow As DataRow
OneDataRow = drT(0)
OneDataRow.Item("FirstName") = CType(gRow.FindControl("txtFirst"), TextBox).Text
OneDataRow.Item("LastName") = CType(gRow.FindControl("txtLast"), TextBox).Text
OneDataRow.Item("City") = CType(gRow.FindControl("txtCity"), TextBox).Text
OneDataRow.Item("Description") = CType(gRow.FindControl("txtDescription"), TextBox).Text
OneDataRow.Item("Nights") = CType(gRow.FindControl("txtNights"), TextBox).Text
' combo box
Dim cboRank As DropDownList = gRow.FindControl("cboRank")
If cboRank.Text = "Select" Then
OneDataRow("Rating") = DBNull.Value
Else
OneDataRow("Rating") = cboRank.SelectedItem.Value
End If
End If
Next
End Sub
Note how we dumped "index" and now do search by PK. (note that datakeys by index WILL be ok, since LV only displays rows not deleted.
Edit4: Delete code - full code listing
As noted, I did post some vb code by mistake.
So, here is the full code listing:
DataTable rstRating = new DataTable();
DataTable rstData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
Session["rstData"] = rstData;
Session["rstRating"] = rstRating;
}
else
{
rstData = (DataTable)Session["rstData"];
rstRating = (DataTable)Session["rstRating"];
}
}
void LoadData()
{
// set combo box source
rstRating = MyRst("SELECT ID, Rating FROM tblRating ORDER BY ID");
rstData = MyRst("SELECT * FROM tblHotelsA ORDER BY HotelName");
LVHotels.DataSource = rstData;
LVHotels.DataBind();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
protected void LVHotels_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DropDownList dl = (DropDownList)e.Item.FindControl("DropDownList1");
dl.DataSource = rstRating;
dl.DataBind();
dl.Items.Insert(0, new ListItem("Please Select", "0"));
// now set to current data row
DataRowView OneRow = (DataRowView)e.Item.DataItem;
if (OneRow["Rating"] != null)
dl.SelectedValue = OneRow["Rating"].ToString();
}
}
protected void cmdSave_ServerClick(object sender, EventArgs e)
{
SaveAllData();
// data saved - move on to next page
// Response.Redirect("MyMain.aspx");
}
protected void cmdAddNew_ServerClick(object sender, EventArgs e)
{
DataRow NewRow = rstData.NewRow();
rstData.Rows.Add(NewRow);
// show this row
LVHotels.DataSource = rstData;
LVHotels.DataBind();
}
void SaveAllData()
{
GridToTable(); // move grid back to table
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * FROM tblHotelsA WHERE ID = 0", conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
// rstData.AcceptChanges()
}
}
}
protected void cmdCancel_ServerClick(object sender, EventArgs e)
{
// cancel without save - go back some place to other page
// Response.Redirect("MyMain.aspx");
}
void GridToTable()
{
// send LV rows back to our table.
foreach (ListViewItem rRow in LVHotels.Items)
{
int PK = (int)LVHotels.DataKeys[rRow.DisplayIndex]["ID"];
// get row by PK
DataRow[] drT = rstData.Select("ID = " + PK,"", DataViewRowState.CurrentRows);
if (drT.Length > 0)
{
DataRow OneDataRow = drT[0];
OneDataRow["FirstName"] = ((TextBox)rRow.FindControl("txtFirst")).Text;
OneDataRow["LastName"] = ((TextBox)rRow.FindControl("txtLast")).Text;
OneDataRow["HotelName"] = ((TextBox)rRow.FindControl("txtHotel")).Text;
DropDownList dlRating = (DropDownList)rRow.FindControl("DropDownList1");
if (dlRating.SelectedIndex == 0)
OneDataRow["Rating"] = DBNull.Value;
else
OneDataRow["Rating"] = dlRating.SelectedItem.Value;
}
}
}
protected void cmdDelete_ServerClick(object sender, EventArgs e)
{
GridToTable();
HtmlButton btn = (HtmlButton)sender;
ListViewItem gRow = (ListViewItem)btn.NamingContainer;
int PK = (int)LVHotels.DataKeys[gRow.DataItemIndex]["ID"];
// get row by PK
DataRow[] drT = rstData.Select("ID = " + PK, "", DataViewRowState.CurrentRows);
drT[0].Delete();
LVHotels.DataSource = rstData;
LVHotels.DataBind();
}
protected void cmdUndo_ServerClick(object sender, EventArgs e)
{
LoadData();
Session["rstData"] = rstData;
}
And the results look like this:
Markup for the buttons was:
<br />
<button id="cmdSave" runat="server" class="btn" onserverclick="cmdSave_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-floppy-saved"> Save</span>
</button>
<button id="cmdCancel" runat="server" class="btn" style="margin-left:15px" onserverclick="cmdCancel_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-arrow-left"> Back/Cancel</span>
</button>
<button id="cmdUndo" runat="server" class="btn" style="margin-left:15px"
onserverclick="cmdUndo_ServerClick" >
<span aria-hidden="true" class="glyphicon glyphicon-refresh"> Undo Edits</span>
</button>
And I was going to add a bootstrap dialog for confirms - the built in browser ones look beyond ugly. But above should clear up the syntax for htis to work.

Dropdownlist not showing correct selected value in ASP.NET Repeater Web application

I have a few ASP.NET Repeaters that have drop down lists in them and they all need to be populated with the correct information and then display the selected value for each data row it is displaying. In one repeater (CompanyRepeater), the correct selected value is chosen. In another repeater (SoldRepeater), the correct selected value is NOT chosen. So the drop down list in CompanyRepeater does work but the one in SoldRepeater does not work. The code is the same for both repeaters and I cannot figure out why the second one is not working. Both drop down lists populate with the correct information but the second repeater does not display the correct selected value. Please help me figure out why the correct selected value is not being selected. Below is my code. Please let me know if there is anymore information needed to help me. Any help is much appreciated. First is my front end code.
<asp:Repeater ID="CompanyRepeater" runat="server" OnItemDataBound="CompanyRepeater_ItemDataBound" OnItemCommand="CompanyRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Company</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtDate" runat="server" Text='<%#Eval("Date") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>OldName
<br />
<asp:TextBox ID="txtOldNameChange" Text='<%#Eval("OldName") %>' runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:
<asp:DropDownList ID="ddlCountry" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"></asp:DropDownList>
<br /> State:
<asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>
</td>
<td>New Name
<br />
<asp:TextBox ID="txtNewNameChange" runat="server" Text='<%#Eval("NewName") %>'></asp:TextBox>
</td>
<td rowspan="3" style="width: 50px; float: right;">
<asp:Button ID="btnUpdateName" runat="server" Text="Update" CommandName="Update" />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
<hr />
<asp:Repeater ID="SoldRepeater" runat="server" OnItemDataBound="SoldRepeater_ItemDataBound" OnItemCommand="SoldRepeater_ItemCommand">
<ItemTemplate>
<table>
<tr>
<td colspan="3" style="text-align: center;">
<h3 style="font-weight: bold;">Sold Event</h3>
</td>
</tr>
<tr>
<td>Event Date:
<br />
<asp:TextBox ID="txtSoldDate" runat="server" Text='<%#Eval("EventDate") %>'></asp:TextBox>
<asp:Label ID="lblCompID" runat="server" Text='<%#Eval("CompID") %>' Visible="false"></asp:Label>
</td>
<td rowspan="2">Notes:
<br />
<asp:TextBox ID="txtSoldNotes" TextMode="MultiLine" Height="100px" Text='<%#Eval("Notes") %>' runat="server"></asp:TextBox>
</td>
<td>Sold to Company
<br />
<asp:TextBox ID="txtSoldTo" Text='<%#Eval("SoldToCompany") %>' runat="server"></asp:TextBox>
<br /> Sold to Type
<asp:DropDownList ID="ddlSoldTo" runat="server"></asp:DropDownList>
</td>
<td rowspan="2">
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandName="Update" CommandArgument='<%#Eval("CompID") %>' />
<br />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?')" CommandName="Delete" CommandArgument='<%#Eval("CompID") %>' />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorTemplate>
<p> </p>
<br />
</SeparatorTemplate>
</asp:Repeater>
This is my backend code
protected void Page_Load(object sender, EventArgs e)
{
_cID = Convert.ToInt32(Request.QueryString["CompID"]);
if (!Page.IsPostBack)
{
PopulateCompanyRepeater();
PopulateSoldEvent();
}
}
private void PopulateCompanyRepeater()
{
DALAccessData a = new DALAccessData(connString);
_listInfo = a.GetCompInfo(_cID);
CompanyRepeater.DataSource = _listInfo;
CompanyRepeater.DataBind();
}
private void PopulateSoldEvent()
{
DALSectionAccessData a = new DALSectionAccessData(connString);
_listEvents = a.GetSoldEvents(_cID);
SoldRepeater.DataSource = _listEvents;
SoldRepeater.DataBind();
}
protected void CompanyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)e.Item.FindControl("ddlState");
Corp co = (Corp)e.Item.DataItem;
Corp st = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT a.Country_ID, a.CountryName FROM States c INNER JOIN Countries a ON a.Country_ID = c.Country_ID";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "CountryName";
ddl.DataValueField = "Country_ID";
ddl.DataBind();
cn.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (co.Country_ID == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
}
else
{
ddl.Items[i].Selected = false;
}
}
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT DISTINCT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl2.DataSource = ds.Tables[0];
ddl2.DataTextField = "StateName";
ddl2.DataValueField = "StateID";
ddl2.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl2.Items.Count; i++)
{
if (!String.IsNullOrEmpty(ddl2.Items[i].Value))
{
if (st.StateID == Convert.ToInt32(ddl2.Items[i].Value))
{
ddl2.Items[i].Selected = true;
}
else
{
ddl2.Items[i].Selected = false;
}
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlCountry");
DropDownList ddl2 = (DropDownList)CompanyRepeater.Items[0].FindControl("ddlState");
ddl2.Items.Clear();
using(SqlConnection conn = new SqlConnection(connString))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = " + ddl.SelectedValue;
cmd.Connection = conn;
conn.Open();
using(SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem _listStates = new ListItem();
_listStates.Text = sdr["StateName"].ToString();
_listStates.Value = sdr["StateID"].ToString();
ddl2.Items.Add(_listStates);
}
}
}
}
ddl2.AppendDataBoundItems = true;
ddl2.Items.Insert(0, new ListItem("Select a State", "-1"));
ddl2.SelectedIndex = -1;
}
protected void SoldRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddl = (DropDownList)e.Item.FindControl("ddlSoldTo");
int x = ((CorpEvents)e.Item.DataItem).SoldToTypeID;
//Corp x = (Corp)e.Item.DataItem;
SqlDataAdapter sda;
DataSet ds = new DataSet();
try
{
using(cn = new SqlConnection(connString))
{
string s = "SELECT SoldToTypeID, SoldToTypeName FROM SoldToType";
cn.Open();
sda = new SqlDataAdapter(s, cn);
sda.Fill(ds);
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "SoldToTypeName";
ddl.DataValueField = "SoldToTypeID";
ddl.DataBind();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
}
}
My data access layer code
public List <Corp> GetCompInfo(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, CONVERT(varchar(10), a.Date, 120) AS Date, a.Notes, b.StateID, b.OldName, b.NewName, c.Country_ID FROM NameChange b INNER JOIN CompanyInfo a ON a.CompID = b.CompID INNER JOIN States c ON c.StateID = b.StateID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.NewName = row["NewName"].ToString();
e.OldName = row["OldName"].ToString();
e.StateID = Convert.ToInt32(row["StateID"].ToString());
e.Notes = row["Notes"].ToString();
e.CountryID = Convert.ToInt32(row["Country_ID"].ToString());
e.Date = Convert.ToDateTime(row["Date"].ToString());
e.Date.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
public List <Corp> GetSoldEvents(int a)
{
List <Corp> _listInfo = new List <Corp> ();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
//create the connection and command objects
SqlConnection connection = new SqlConnection(_dbConnection);
SqlCommand command = new SqlCommand();
//populate the command object
command.Connection = connection;
command.CommandText = "SELECT a.CompID, a.Notes, a.Date, b.SoldToCompany, c.SoldToTypeName, c.SoldToTypeID FROM CompanyInfo a INNER JOIN SoldEvent b ON a.CompID = b.CompID INNER JOIN SoldToType c ON b.SoldToTypeID = c.SoldToTypeID WHERE a.CompID = " + a;
using(connection)
{
using(command)
{
connection.Open();
ds.Load(command.ExecuteReader(), LoadOption.OverwriteChanges, new string[] {
"MyTable"
});
dt = ds.Tables["MyTable"];
}
}
foreach(DataRow row in dt.Rows)
{
Corp e = new Corp();
e.CompID = Convert.ToInt32(row["CompID"].ToString());
e.SoldToCompany = row["SoldToCompany"].ToString();
e.SoldToTypeName = row["SoldToTypeName"].ToString();
e.SoldToTypeID = Convert.ToInt32(row["SoldToTypeID"].ToString());
e.Notes = row["Notes"].ToString();
e.EventDate = Convert.ToDateTime(row["Date"].ToString());
e.EventDate.ToShortDateString();
_listInfo.Add(e);
}
return _listInfo;
}
IMHO, your method of setting the selected value is rather cumbersome. This entire section of code:
for (int i = 0; i < ddl.Items.Count; i++)
{
if (x == Convert.ToInt32(ddl.Items[i].Value))
{
ddl.Items[i].Selected = true;
//i = 9;
}
else
{
ddl.Items[i].Selected = false;
}
}
Can be replaced with a single line:
ddl.SelectedValue = x.ToString();
In addition, once you do find the matching value you continue to loop on the items, rather than exiting out of the loop.
Try these changes, they may solve the problem for you.
A few other items that I noticed:
The code to retrieve the SoldToType is called for each item in the
repeater. I would suggest retrieving this data once and referencing
it for each item, rather than going to the db each time.
Your SQL code is wide open to SQL injection. Use parameterized queries, like so:
cmd.CommandText = "SELECT StateName, StateID FROM States WHERE Country_ID = #CountryID";
...
cmd.Parameters.AddWithValue("CountryID", ddl.SelectedValue);

How to bind values in usercontrol dropdownlist?

I bind the values in usercontrol dropdownlist
But when I add the usercontrol row that time values are not binded in dropdownlist
Code:
.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TimesheetUserControl.ascx.cs" Inherits="Portal.TimesheetUserControl" %>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownActivities" Width="150px" runat="server"></asp:DropDownList>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</td>
</tr>
.aspx
<uc:Timesheet ID="Timesheet" runat="server" />
<asp:Repeater ID="rpt1" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
BindActivities();
}
}
protected void BindActivities()
{
DropDownList dropActivities = Timesheet.FindControl("DropDownActivities") as DropDownList;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (IsPostBack)
{
GenerateControls();
}
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
TimesheetUserControl ctrl = (TimesheetUserControl)Page.LoadControl("TimesheetUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
Button thisButton = (Button)sender;
List<string> temp = null;
var uc = (TimesheetUserControl)this.LoadControl(#"TimesheetUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
In the below image if Click add button rows are added but in second values are not binded in dropdownlist
Any ideas? Thanks in advance.
find the user controls by the id you given and then you can find the DropDownList inside the usercontrol.
protected void BindActivities()
{
foreach (string controlName in NoOfControls)
{
TimesheetUserControl userControl = Timesheet.FindControl(controlName) as TimesheetUserControl;
if(userControl == null) return;
DropDownList dropActivities = userControl.FindControl("DropDownActivities") as DropDownList;
if(dropActivities == null) return;
DbConnection.Open();
OleDbCommand cmd1 = new OleDbCommand("select designation from emp_master where username = '" + username + "'", DbConnection);
OleDbDataAdapter da = new OleDbDataAdapter(Deptcmd);
DataSet ds = new DataSet();
da.Fill(ds);
// DbConnection.Close();
dropActivities.DataSource = ds;
dropActivities.DataTextField = "ActivityName";
dropActivities.DataBind();
dropActivities.Items.Insert(0, new ListItem("--Select--", "0"));
}
}

Grabbing values of genered ListBox ASP Controls inside ListView On PostBack

So I've got this:
<asp:ListView runat="server" ID="lvAttributes" DataKeyNames="attribute_id" OnItemDataBound="lvAttributes_ItemDataBound">
<ItemTemplate>
<label class="title">product <%# Eval("name") %></label>
<asp:ListBox DataTextField="value" DataValueField="tag_id" CssClass="chzn-select"
runat="server" ID="lbAttributeTags"></asp:ListBox>
<br />
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholder" runat="server"></div>
</LayoutTemplate>
</asp:ListView>
Now on post back I'd like to get each individual lbAttributeTags selected value. But as you know there might be a single ListBox generated or 100. So how should I approach a solution for this for the many potential possibilities?
Thanks in advance.
Here you have the code to fetch the selected item from the ListBox inside the list view control
asp.net
<form id="form1" runat="server">
<div>
</div>
<asp:ListView runat="server" ID="lvAttributes" DataKeyNames="attribute_id" OnItemDataBound="lvAttributes_ItemDataBound">
<ItemTemplate>
<label class="title">product <%# Eval("name") %></label>
<asp:ListBox DataTextField="value" DataValueField="tag_id" CssClass="chzn-select"
runat="server" ID="lbAttributeTags"></asp:ListBox>
<asp:Button ID="btnInsideLV" runat="server" Text="Inside LV Click" OnCommand="btnInsideLV_Click" CommandArgument='<%# Container.DataItemIndex + 1 %>' /><br />
</ItemTemplate>
<LayoutTemplate>
<div id="itemPlaceholder" runat="server"></div>
</LayoutTemplate>
</asp:ListView>
<asp:Button ID="btnSample" runat="server" Text="Click" OnClick="btnSample_Click" />
<asp:Label ID="lblDisplay" runat="server" />
<asp:Label ID="lblSelectedRowValue" runat="server" />
</form>
c#:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class stackoverflow_12761515 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("attribute_id");
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["attribute_id"] = i + 1;
dr["name"] = "item " + i + 1;
dt.Rows.Add(dr);
}
lvAttributes.DataSource = dt;
lvAttributes.DataBind();
//BindListBox();
}
}
private void BindListBox(ListBox lb)
{
DataTable dt = new DataTable();
dt.Columns.Add("value");
dt.Columns.Add("tag_id");
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["tag_id"] = i + 1;
dr["value"] = "value " + i + 1;
dt.Rows.Add(dr);
}
//ListBox lb = (ListBox)lvAttributes.FindControl("lbAttributeTags");
lb.DataSource = dt;
lb.DataTextField = "value";
lb.DataValueField = "tag_id";
lb.DataBind();
}
protected void lvAttributes_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListBox lb = (ListBox)e.Item.FindControl("lbAttributeTags");
BindListBox(lb);
}
protected void btnSample_Click(object sender, EventArgs e)
{
lblDisplay.Text = string.Empty;
for (int i = 0; i < lvAttributes.Items.Count; i++)
{
ListBox lb = (ListBox)lvAttributes.Items[i].FindControl("lbAttributeTags");
if (lb.SelectedIndex != -1)
{
lblDisplay.Text += lb.SelectedItem.Text + "\n";
}
}
}
protected void btnInsideLV_Click(object sender, CommandEventArgs e)
{
int selectedRow = Convert.ToInt32(e.CommandArgument.ToString());
ListBox lbCurrent = (ListBox)lvAttributes.Items[selectedRow - 1].FindControl("lbAttributeTags");
if (lbCurrent.SelectedIndex != -1)
{
lblSelectedRowValue.Text = "Row selected is : " + selectedRow + " and list item is : " + lbCurrent.SelectedItem.Text;
}
else
{
lblSelectedRowValue.Text = "no item selected";
}
}
}
The 2 button click events have the code which you required. Please let me know if you need anything else.

Selected value on a DropDownList inside of a repeater

I'm adding a dropdwonlist inside of my repeater. Now I need to set a selected value for my dropdownlist.. but I'm not being very successful..
private void PhysicianSource()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Provider oProvider = new Provider();
List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
foreach (ProviderLabel item in lstprovider)
{
DataRow dr = dt.NewRow();
dr[0] = item.ProviderCode.ID.ToString();
dr[1] = item.Name.ToString();
dt.Rows.Add(dr);
}
drpPhysicianCode.DataSource = ds;
drpPhysicianCode.DataMember = "Source";
drpPhysicianCode.DataTextField = "ID";
drpPhysicianCode.DataValueField = "ID";
drpPhysicianCode.DataBind();
}
asp.net
<asp:Repeater ID="rptrPatientList" runat="server" >
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1"
DataTextField="ID" runat="server"
DataValueField="Desc"
SelectedValue='<%# Eval("Code") %>'
DataSource="ds">
</asp:DropDownList>
</td>
</td>
</tr>
nothing happens on my codes.. help me guys I'm just a beginner on this.. thank you very much..
Hi Ian Ace its better to modify your code a little bit
<asp:Repeater ID="rptProductList" runat="server" OnItemDataBound="rptProductList_ItemDataBound">
<ItemTemplate>
<asp:DropDownList runat="server" ID="MyRepeater" AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" >
</asp:DropDownList>
</ItemTemplate>
</asp:Repeater>
Now the code behind should be
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillRepeater();
}
}
}
protected void rptProductList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList MyDropDown= (DropDownList)e.Item.FindControl("MyRepeater");
if (MyDropDown!= null)
{
MyDropDown.DataSource = fillDropDown(MyDropDown);
MyDropDown.DataBind();
}
}
}
private DataSet fillDropDown(DropDownList dropDown)
{
// get your collection and return.
}
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList MyDropDown= (DropDownList)sender;
string item = MyDropDown.SelectedValue;
}
hope the above example helps.
Try setting the selected value after data binding
Don't set the list contents with every postback. Check for Page.IsPostBack(). Note that this only works if you have ViewState enabled.
//Declare Class Scoped DataSet and DataTable variables
DataSet ds;
DataTable dt;
//Bind repeater and DataSource method
private void PhysicianSource()
{
ds = new DataSet();
dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Provider oProvider = new Provider();
List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
foreach (ProviderLabel item in lstprovider)
{
DataRow dr = dt.NewRow();
dr[0] = item.ProviderCode.ID.ToString();
dr[1] = item.Name.ToString();
dt.Rows.Add(dr);
}
drpPhysicianCode.DataSource = ds;
drpPhysicianCode.DataMember = "Source";
drpPhysicianCode.DataTextField = "ID";
drpPhysicianCode.DataValueField = "ID";
drpPhysicianCode.DataBind();
}
//Repeater Item Data Bound event in which we would find Controls to be bound
//and set DataSource and SelectedValue
protected void rptrPatientList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList DropDownList1 = e.Item.FindControl("DropDownList1") as DropDownList;
if (DropDownList1 != null)
{
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.SelectedValue = // DataBinder Eval 'Code' //;
}
}
}
<asp:Repeater ID="rptrPatientList" runat="server" OnItemDataBound="rptrPatientList_ItemDataBound">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1"
DataTextField="ID" runat="server"
DataValueField="Desc"
SelectedValue='<%# Eval("Code") %>'
DataSource="ds">
</asp:DropDownList>
</td>
</td>
</tr>
The problem occurs because the binding of dropdown occurs after that of repeater control. You can use HTML5 custom attributes, to set your dropdown value into a custom attribute, and then setting it as selected value after the dropdown is databinded. I have binded the dropdown using asp:ObjectDataSource
ASPX
<asp:Repeater ID="rptrPatientList" runat="server" >
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
<asp:DropDownList ID="DropDownList1"
DataTextField="ID" runat="server"
DataValueField="Desc"
SetValue='<%# Eval("Code") %>' datasourceid="dsCategory"
datatextfield="ID" datavaluefield="desc" DataMember = "Source" onprerender="DropDownDataBinding">
</asp:DropDownList>
<asp:ObjectDataSource ID="dsCategory" runat="server" SelectMethod="PhysicianSource" TypeName="WebApplication.WebForm1" />
</td>
</td>
</tr>
CodeBehind
protected void DropDownDataBinding(object sender, EventArgs e) //Method to set the selected value on Category dropdown inside repeater
{
DropDownList sel = (DropDownList)sender;
sel.Value = sel.Attributes["SetValue"];
ListItem li = new ListItem("<< Select >>", "");
sel.Items.Insert(0,li);
}
protected DataSet PhysicianSource()
{
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add("Source");
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("Desc", Type.GetType("System.String"));
Provider oProvider = new Provider();
List<ProviderLabel> lstprovider = oProvider.RetrievePhysicianList();
foreach (ProviderLabel item in lstprovider)
{
DataRow dr = dt.NewRow();
dr[0] = item.ProviderCode.ID.ToString();
dr[1] = item.Name.ToString();
dt.Rows.Add(dr);
}
return ds;
}

Categories