How to Rearrange the DropDown values..?


How to Rearrange the DropDown values..? In this Artical i'm trying to explain to re-arrange the dropdown values based upon the dropdown selected values. I want to change value from 5 to 1, then result becomes 1 to 2, 2 to 3, 3 to 4, 4 to 5, 5 to 1. If i change DropDown Value 2 to 7, then result becomes 7 to 6,6 to 5, 5 to 4,4 to 3, 3 to 2,2 to 7.

Artical Summary:



In this Artical i'm trying to explain to re-arrange the dropdown values.
I have a GridView in my Gridview one of the column is DropDownList. I have 7 Rows in my GridView so My DropDownList also having 7 Rows numbers like 1,2,3,4,5,6,7.

for Example i want to change the order details from 5 to 1.
Then 1 becomes to 2,2 becomes to 3, 3 becomes to 4 , 4 becomes to 5 and 5 becomes to 1.

for Example i want to change the order details from 2 to 7.
Then 7 becomes 6,6 becomes 5,5 becomes 4,4 becomes 3, 3 becomes 2 and then 2 becomes 7.

Here i'm effectively handling DataTable objects. So, here please be understand the each and everyRow of DataTable as well as GridView control also. Then only you can understand the logic of this. If you have any more doubts please refer the below attachements then you clearly understood the logic of this.


Source Code:



Design Your Source code as below

1) Design a form.
2) Drag & Drop ListBox Control Which holds all the members.


<asp:ListBox ID="lstMember" runat="server" Width="80%" CssClass="ArialNarrow" ToolTip="List of Member" SelectionMode="Multiple" Height="425px"/>



3) Drag & Drop 2 button controls in a form one is to Add Members from ListBox to GridView control and another one is to remove members from GridView Control.

  
<asp:Button ID="bttnToadd" runat="server" ToolTip="Add To" Text=" >> " OnClick="btnToAdd_OnClick" />

<asp:Button ID="bttnToremove" runat="server" ToolTip="Remove" Text=" << " OnClick="btnToRemove_OnClick" />


4) Drag & Drop GridView Control Which holds all the members added by User.


<asp:GridView ID="gvTo" runat="server" Width="60%" CssClass="ArialNarrow"AutoGenerateColumns="false" ToolTip="Mail To" OnRowDataBound="gvTo_RowDataBound" AllowSorting="true" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowHeader="true">

<Columns>
<asp:TemplateField ItemStyle-Width="10%">
<HeaderTemplate>
<input id="chkSelect" type="checkbox" onclick="CheckAllTo(this)" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Mail To" ItemStyle-Width="65%">
<ItemTemplate>
<asp:Label ID="lblMember_Name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Member_Name") %>' />
<asp:Label ID="lblMember_Id" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Member_Id") %>'Visible="false" />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField ItemStyle-Width="25%">
<HeaderTemplate >Display Order</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlSortTo" runat="server" ToolTip="Sort" AutoPostBack="true" OnSelectedIndexChanged="ddlSortTo_OnSelectedIndexChanged" ValidationGroup="To" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


JavaScript:



Use javascript code for selecting / deselcting all rows to remove from GridView control.


<script type="text/javascript" language="javascript">

function CheckAllTo(oCheckbox) {
var gvTo = document.getElementById("<%=gvTo.ClientID %>");

for (i = 1; i < gvTo.rows.length; i++) {
gvTo.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = oCheckbox.checked;
}

}


</script>





Code Behind:



After Design the Source Code implement your Coding using the follow snippet.



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Services;

public partial class AlertMembers : System.Web.UI.Page
{
//this event will raise on page load itself.
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
Bind_Member();
FixGridHeaderTo();
}

}

//when there is no data in GV then this method helps you to show empty Gridview with Headers.

protected void FixGridHeaderTo()
{
DataTable dt = new DataTable();
dt.Columns.Add("Member_Id");
dt.Columns.Add("Member_Name");
dt.Columns.Add("Receiver_Type");
dt.Columns.Add("Sort_By");
dt.Columns.Add("Sort_By_Dup");
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dt.NewRow().ItemArray);
gvTo.DataSource = dt;
gvTo.DataBind();
gvTo.Rows[0].Visible = false;
gvTo.Rows[0].Controls.Clear();
}

//Bind member details

protected void Bind_Member()
{
BSLayer obj = new BSLayer();
DataSet ds = //Bind data;
DataTable dt = ds.Tables[0];

//Sort the data using below code
dt.DefaultView.Sort = "Member_Desc";

// bind data to listbox control

lstMember.DataSource = dt;
lstMember.DataTextField = "Member_Name";
lstMember.DataValueField = "Member_Id";
lstMember.DataBind();
}
protected void btnToAdd_OnClick(object sender, EventArgs e)
{
BSLayer obj = new BSLayer();

DataTable dtTo = ViewState["PAM"] as DataTable;

//filter the data using below code

DataView dvTo = dtTo.DefaultView;
dvTo.RowFilter = "Receiver_Type=2";

DataRow drTo;

// to check the selected members in the listbox control

if (lstMember.SelectedIndex > -1)
{
for (int i = 0; i < lstMember.Items.Count; i++)
{
if (lstMember.Items[i].Selected)
{
DataColumn[] dtToAttachmentPK = new DataColumn[1];

//store the member details into one datatable and assign the primary key of the datatable. See the below code helps you.

dtToAttachmentPK[0] = dtTo.Columns["Member_Id"];
dtTo.PrimaryKey = dtToAttachmentPK;

if (dtTo.Rows.Find(lstMember.Items[i].Value) == null)
{

drTo = dtTo.NewRow();
drTo["Member_Name"] = lstMember.Items[i].Text;
drTo["Member_Id"] = lstMember.Items[i].Value;
if (dvTo.ToTable().Rows.Count >= 0)
{
for (int j = 0; j <= dvTo.ToTable().Rows.Count; j++)
{
//for sorting the DropDown number
drTo["Sort_By"] = 1 + j;
//Duplicate Value of the Sorted Record
drTo["Sort_By_Dup"] = 1 + j;
}
}
drTo["Receiver_Type"] = "2";

// Add rows to DataTable
dtTo.Rows.Add(drTo);

}
}
}
}

//After Adding all rows to DataTable Save the details using below.

dtTo.AcceptChanges();

//Sorting & filtering the data using the below code.

DataView dv = dtTo.AsDataView();
dv.Sort = "Receiver_Type,Sort_By_Dup ASC";
dtTo = dv.ToTable();
ViewState["PAM"] = dtTo;

dvTo = dtTo.DefaultView;
dvTo.RowFilter = "Receiver_Type=2";
dvTo.Sort = "Sort_By_Dup ASC";

if (dvTo.ToTable().Rows.Count != 0)
{
gvTo.DataSource = dvTo;
gvTo.DataBind();

for (int i = 0; i < gvTo.Rows.Count; i++)
{
dtTo = dvTo.ToTable();
//find the dropdown control from GV

DropDownList ddl = (DropDownList)gvTo.Rows[i].FindControl("ddlSortTo");
//Assign the Sorted value to DropDown Control.

ddl.SelectedValue = dtTo.Rows[i]["Sort_By"].ToString();
}
}
else
{
//Gv Dont have records then Execute this method to display
// empty Row With Headers.
FixGridHeaderTo();
}

lstMember.SelectedIndex = -1;
}

//Remove Member details from GridView .

protected void btnToRemove_OnClick(object sender, EventArgs e)
{
BSLayer obj = new BSLayer();

DataTable dtTo = ViewState["PAM"] as DataTable;

//Filter Data Using below snippet.

DataView dvTo = dtTo.DefaultView;
dvTo.RowFilter = "Receiver_Type=2";

DataTable dt = dvTo.ToTable();

foreach (GridViewRow gvrTo in gvTo.Rows)
{

//find checkbox control in GV
CheckBox chkSelect = gvrTo.FindControl("chkSelect") as CheckBox;
//Remove Records based on checkBox Selection.

if (chkSelect.Checked == true)
{
DataColumn[] dtToAttachmentPK = new DataColumn[1];

//Assign PK column to DataTable.
dtToAttachmentPK[0] = dtTo.Columns["Member_Id"];
dtTo.PrimaryKey = dtToAttachmentPK;

Label lblMember_Id = gvrTo.FindControl("lblMember_Id") as Label;

//Delete from DB

if (dtTo.Rows.Find(lblMember_Id.Text) != null)
{
//Delete from DataTable.

dtTo.Rows.Find(lblMember_Id.Text).Delete();
}

}
}

dvTo = dtTo.DefaultView;
dvTo.RowFilter = "Receiver_Type=2";
dvTo.Sort = "Sort_By_Dup ASC";
dt = dvTo.ToTable();


//Rearrange the DataTable Values

for (int j = 0; j < dt.Rows.Count; j++)
{
int val = Convert.ToInt32(dt.Rows[j][3]);
val = j + 1;
dt.Rows[j][4] = val;
dt.Rows[j][3] = dt.Rows[j][4];
}


dtTo.Merge(dt);
dtTo.AcceptChanges();
DataView dv = dtTo.AsDataView();
dv.Sort = "Sort_By_Dup ASC";
dtTo = dv.ToTable();
ViewState["PAM"] = dtTo;

if (dt.Rows.Count != 0)
{

/Bind GV after delete Records.

gvTo.DataSource = dt;
gvTo.DataBind();

for (int i = 0; i < gvTo.Rows.Count; i++)
{
//find DropDown Control in GV.

DropDownList ddl = (DropDownList)gvTo.Rows[i].FindControl("ddlSortTo");
//Re-arrange DropDown Values after deleting records.

ddl.SelectedValue = dt.Rows[i]["Sort_By"].ToString();

}
}
else
{

//GV don't have any rows then only execute this part.

FixGridHeaderTo();
}
}

//for each and evry row of GV this event raised.

protected void gvTo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
BSLayer obj = new BSLayer();

DataTable dtTo = ViewState["PAM"] as DataTable;
DataView dvTo = dtTo.DefaultView;

dvTo.RowFilter = "Receiver_Type=2";
dvTo.Sort = "Sort_By_Dup ASC";

DataTable dt = dvTo.ToTable();

for (int j = 0; j < dt.Rows.Count; j++)
{
int val = Convert.ToInt32(dt.Rows[j][3]);
val = j + 1;
dt.Rows[j][4] = val;
dt.Rows[j][3] = dt.Rows[j][4];
}
dt.AcceptChanges();

//Find dropdown control
DropDownList ddlSortTo = (DropDownList)e.Row.Cells[2].FindControl("ddlSortTo");


//assign datatable result to DropDownList.
ddlSortTo.DataSource = dt;

ddlSortTo.DataTextField = "Sort_By_Dup";
ddlSortTo.DataValueField = "Sort_By_Dup";

ddlSortTo.DataBind();

}
}


//This is the main part of our requirement..
//Here when i change the DropDown values it's rearrnage the remaining
//Values based on selection.

protected void ddlSortTo_OnSelectedIndexChanged(object sender, EventArgs e)
{
BSLayer obj = new BSLayer();

DataTable dtTo = ViewState["PAM"] as DataTable;


DataView dvTo = dtTo.DefaultView;
dvTo.RowFilter = "Receiver_Type=2";

DataTable dt = new DataTable();

dt = dvTo.ToTable();
DropDownList ddl1 = sender as DropDownList;
foreach (GridViewRow myRow in gvTo.Rows)
{

DropDownList ddl = myRow.FindControl("ddlSortTo") as DropDownList;
if (ddl.ClientID == ddl1.ClientID)
{

Label lblMember_Id = myRow.FindControl("lblMember_Id") as Label;
lblMember_Id.Text = ddl1.SelectedValue;
//index of the row.
int index = myRow.RowIndex;
dt.Rows[index]["Sort_By"] = lblMember_Id.Text;


for (int i = 0; i < dt.Rows.Count; i++)
{
//here i'm comparing Sort_By and Sort_By_Dup col's

if (dt.Rows[i][3] != dt.Rows[i][4])
{
//here i'm comparing Sort_By and Sort_By_Dup col's

// 2 is changed to 7 then only this part executed.

if (Convert.ToInt32(dt.Rows[i][3]) < Convert.ToInt32(dt.Rows[i][4]))

{

int MinVal = Convert.ToInt32(dt.Rows[i][3]);
int MaxVal = Convert.ToInt32(dt.Rows[i][4]);

//assign modified values to DataTable.

for (int j = 0; j < dt.Rows.Count; j++)
{
int increment = Convert.ToInt32(dt.Rows[j][4]);
if (MinVal <= increment && increment < MaxVal)
{

increment = increment + 1;
dt.Rows[j][4] = increment;
}

else
{
dt.Rows[j][4] = dt.Rows[j][3];
}
dt.Rows[j][3] = dt.Rows[j][4];

}

}

// 5 is changed to 1 then only this part executed.

else if (Convert.ToInt32(dt.Rows[i][3]) > Convert.ToInt32(dt.Rows[i][4]))
{
int MaxVal = Convert.ToInt32(dt.Rows[i][3]);
int MinVal = Convert.ToInt32(dt.Rows[i][4]);

for (int j = 0; j < dt.Rows.Count; j++)
{
int decrement = Convert.ToInt32(dt.Rows[j][4]);
if (MaxVal >= decrement && decrement > MinVal)
{
decrement = decrement - 1;
dt.Rows[j][4] = decrement;
}
else
{
dt.Rows[j][4] = dt.Rows[j][3];
}
dt.Rows[j][3] = dt.Rows[j][4];

}

}
}
}

//After rearrange the values saving result in DataTable.

dt.AcceptChanges();
dtTo.AcceptChanges();

for (int i = 0; i < dtTo.Rows.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
if (Convert.ToInt32(dtTo.Rows[i][0]) == Convert.ToInt32(dt.Rows[j][0]))
{
dtTo.Rows[i][4] = dt.Rows[j][4];
dtTo.Rows[i][3] = dt.Rows[j][3];
}

}
}

break;
}
}

//modified results assign to GV and DropDownLsit also.

ViewState["PAM"] = dtTo;
gvTo.DataSource = dt;
gvTo.DataBind();
for (int i = 0; i < gvTo.Rows.Count; i++)
{
DropDownList ddlTo = (DropDownList)gvTo.Rows[i].FindControl("ddlSortTo");
ddlTo.SelectedValue = dt.Rows[i][4].ToString();
}
}

}



Attachments

Article by naveensanagasetti
I hope you enjoyed to read my article, If you have any queries out of this then please post your comments.

Follow naveensanagasetti or read 139 articles authored by naveensanagasetti

Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: