Appending text from gridview and sort them - c#

I have written the code in ASP.NET application like
protected void chkbox_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkbox = sender as CheckBox;
GridViewRow currentRow = chkbox.NamingContainer as GridViewRow;
Label lblJurisdiction = grdView.Rows[currentRow.RowIndex].FindControl("lblJurisdiction") as Label;
RequiredFieldValidator rfv = grdView.Rows[currentRow.RowIndex].FindControl("ValReqED") as RequiredFieldValidator;
RequiredFieldValidator rfvExpD = grdView.Rows[currentRow.RowIndex].FindControl("ValReqExpD") as RequiredFieldValidator;
RequiredFieldValidator rfvLN = grdView.Rows[currentRow.RowIndex].FindControl("ValReqLN") as RequiredFieldValidator;
if (!chkbox.Checked)
{
rfv.Enabled = false;
rfvExpD.Enabled = false;
rfvLN.Enabled = false;
string JurisdictionRemoved = lblJurisdiction.Text + ",";
string Jurisdiction = txtJurisdiction.Text;
string ReplacedJurisdiction = Jurisdiction.Replace(JurisdictionRemoved, "");
txtJurisdiction.Text = ReplacedJurisdiction;
}
else
{
string Jurisdiction = txtJurisdiction.Text;
txtJurisdiction.Text = Jurisdiction + "," + lblJurisdiction.Text.ToString();
}
}
Note that string Jurisdictions contains set of Jurisdictions like
Delaware,Georgia,Illinois,Kansas,Maine
And string JurisdictionRemoved contains only one jurisdiction like (where user will uncheck the checkbox)
Georgia
Then txtJurisdicton must contain
Delaware,Illinois,Kansas,Maine
if string JurisdictionRemoved contains "Maine" then above code doesnot works, it is not removed.
Now I want that whenever user will uncheck the checkbox that Jurisdiction should be removed from txtJurisdiction textbox and whenever user will check the checkbox the corresponding jurisdiction should be appended to the txtJurisdiction. Let us suppose that user has checked "Georgia" again
then the textbox should contain
Delaware,Georgia,Illinois,Kansas,Maine
The above code doesn't work like this. Also I want it append checked jurisdiction in the textbox alphabetically and should eliminate the redundant state. Please help me!!!

To overcome this issue you can do like this
split conman separated list to an array using split function
Remove the text from the array using condition
User String.Join method to create new string.
Assign that value to your textbox.
Example
List<String> Items = Jurisdiction.Split(",");
Items.Remove( lblJurisdiction.Text);
string NewX = String.Join(",", Items.ToArray());

Related

how to assign comma seperated string to combox with multi selection mode in asp.net?

In asp.net , I need to assign back the values to textbox,dropdown and combobox values back to respective controls. I already prepopulated those dropdown and combobox with their respective values. I can see value in dropdown but not not in combobox since combobox is multiselector with Comma (',').
Note : I m getting comma seperated values as one single string and assigning to combobox .
I tried with the below code, but the combobox is not getting its value back.
if (oDs.Tables[0].Rows.Count > 0)
{
if (oDs.Tables[0].Rows.Count == 1)
{
textbox1.Text = oDs.Tables[0].Rows[0].ItemArray[0].ToString();
textbox2.Text = oDs.Tables[0].Rows[0].ItemArray[1].ToString();
textbox3.Text = oDs.Tables[0].Rows[0].ItemArray[2].ToString();
dropdown1.SelectedItem.Text = oDs.Tables[0].Rows[0].ItemArray[4].ToString();
dropdown2.SelectedItem.Text = oDs.Tables[0].Rows[0].ItemArray[5].ToString();
combbox1.SelectedText =oDs.Tables[0].Rows[0].ItemArray[6].ToString();**
}
}
}
Try something like this:
string[] csvFields = csvString.Split(',');
comboBox1.ItemsSource = csvFields;

Access controls that were created at run time

In my form i have a "plus-button", when the user click on it a new TextBox is added to the form:
private void btnPlus_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Name = "textBox" + countTb.ToString();
this.Controls.Add(tb);
countTb++;
}
My problem is: I don't know how to access these TextBoxes.
I have a save-button, when user clicks it i have to save all TextBox.Text into database, but I don't know how to find them.
You could use Controls.OfType if the TextBoxes are on top of the form:
var allTextBoxes = this.Controls.OfType<TextBox>();
foreach(TextBox txt in allTextBoxes)
{
// ...
}
Another approach is to use ControlCollection.Find to find controls with a given name:
for(int i = 1; i <= countTb; i++)
{
Control[] txtArray = this.Controls.Find("textBox" + i, true); // recursive search
if (txtArray.Length > 0)
{
TextBox txt = (TextBox)txtArray[0];
}
}
you can easily save button names on array or you can access to form text boxes from --> this.controls
To get all of the TextBoxes on the form, you can do the following:
var textBoxes = this.Controls.OfType<TextBox>();
Then you can iterate over them all to get their text values:
foreach(var textBox in textBoxes)
{
var text = textBox.Text;
//do something to save the values.
}
One of the best ways to access the text box after you have created it would be to insert it into an array or list, this way you would be able to iterate through that list/array to access any number of text boxes and save the data inside to a database.
If you want to save all TextBox.Text values on the form in one comma-delimited string:
var allText = string.Join(",", Controls.OfType<TextBox>().Select(x => x.Text));
You'll need to clarify your question more, if this won't work.
This will grab the value of every TextBox on the form, so if you don't want to save the values from some, you'll need to filter them out first.
If you want a list, so you can save one record per TextBox, then remove string.Join.

DropDownList lose index after PostBack

I have a dropdown which I fill with data from a SQL server.
I fill the dropdown dynamically in the Page_Init() Event.
Depending on the Value, a ListItem is selected.
Now the problem is, that when I select another Item in the dropdown, that after the postback the selection is reset to the first item in the dropdownlist.
This here is a basic version of my code which does not work:
ArrayList AD_Group_Members = ActiveDirectory.GetMemberOfGroup("AD-Group");
ArrayList ListMachines = SQLQuery.Read("Database", "SELECT idVM, RandomString, Computername, Owner, FROM VM ORDER BY Computername");
for (int i = 0; i < ListMachines.Count; i++)
{
String RandomString = ((Hashtable)ListMachines[i])["RandomString"].ToString();
String Owner = ((Hashtable)ListMachines[i])["Owner"].ToString();
DropDownList DropDownList_Owner = new DropDownList();
DropDownList_Owner.ID = "DropDownList_Owner_" + RandomString;
DropDownList_Owner.Width = Unit.Percentage(95);
DropDownList_Owner.AutoPostBack = true;
DropDownList_Owner.EnableViewState = true;
DropDownList_Owner.SelectedIndexChanged += DropDownList_Owner_SelectedIndexChanged;
Div_Test.Controls.Add(DropDownList_Owner);
for (int y = 0; y < AD_Group_Members.Count; y++)
{
ListItem ListItem = new ListItem();
ListItem.Value = Owner;
ListItem.Text = ((Hashtable)AD_Group_Members[y])["GivenName"].ToString() + " " + ((Hashtable)AD_Group_Members[y])["Surname"].ToString();
if (((Hashtable)AD_Group_Members[y])["Username"].ToString().Equals(Owner))
{
ListItem.Selected = true;
}
DropDownList_Owner.Items.Add(ListItem);
}
}
Where is the issue in my code, that it doesn't work but the example.
Thank in Advance
You have to populate your dropdownlist under this condition on pageload.
Because on every post back your ddl is populated again and loses its selected index.
if (!IsPostBack)
{
//PopulateYourDDL here
}
You filled dropdown in Page_Init() which gets called in every postback and refill your dropdown and hence loses selectedindex.So you have to fill your dropdown inside !ispostback block
if (!IsPostBack)
{
//fill your dropdown here
}
I think the you should have unique values for the dropdown. Also as you have duplicate values in data value field the problem is occurring. It is looking for the first match and selecting it. You could try to fabricate the values which you could uniquely identify. Something like below:
COLUMN_NAME DATA_TYPE
a a_decimal
b b_decimal
c c_decimal
d d_int
e e_int
f f_varchar
g g_varchar
h h_varchar
i i_varchar
j j_varchar
Check out this Useful Source!!!
I hope it helps!!! Have a close look at those comments in the accepted answer section !!!
Also avoid using SelectedIndex_Changed() functions while dealing with Dynamically generated Web controls. Bind the DropdownList under Page_Init() or Page_PreInit(). If you want to perform some functions upon DropDownlist Selection Check out this! to determine the WebControl ID which is triggered and then perform an unique function in the Page_PreInit() or Page_Init().

dynamic textbox near label in C#

Sorry for reposting this but I haven't figure out how to do it.
string str = string.Empty;
foreach (ListItem item in this.CheckBoxList1.Items)
{
if (item.Selected)
{
str += item.Value + "<br><br>";
TextBox txt1 = new TextBox();
form1.Controls.Add(txt1);
}
}
lbl1.Text = str;
This brings up a textbox each time I check a value but I want to bring the textbox near each selected value that I retain in the label. So value1 textbox1, value2 textbox2....It's asp.net web application.
Why do you want to use the same label?
U could do:
foreach (ListItem item in this.CheckBoxList1.Items)
{
if (item.Selected)
{
Label label = new Label();
label.Text = item.Value;
TextBox txt1 = new TextBox();
form1.Controls.Add(label);
form1.Controls.Add(txt1);
}
}
you also might have to assign id to the textboxes if you are planning to retrieve user input from them.
But if you only have limited number of fields u could use static fields, and change its visibility as Tim stated
I don't really know what you plan to do but why dont you define a CSS class for both the label object and the textbox object using the same y- but alternate x-coordinates.

Passing values from 2 dropdown boxes

I have two different dropdown boxes with prefilled selection items. I am trying to pass all of the users selected items and return data based on it. I am able to retrieve data based on the first dropdown list but for the second dropdown 'null' gets passed in. Here is my code:
resultSummaryViewModel.ReportFrame = new FramedViewModel();
if (string.IsNullOrEmpty(resultSummaryViewModel.Value)) return;
string viewValue = resultSummaryViewModel.Value.Substring(0, resultSummaryViewModel.Value.IndexOf("|"));
string viewType = resultSummaryViewModel.Value.Substring(resultSummaryViewModel.Value.IndexOf("|") + 1);
//if (string.IsNullOrEmpty(resultSummaryViewModel.CValue)) return;
string cTypeValue = resultSummaryViewModel.CValue.Substring(0, resultSummaryViewModel.CValue.IndexOf("|"));
string cType = resultSummaryViewModel.CValue.Substring(resultSummaryViewModel.CValue.IndexOf("|") + 1);
resultSummaryViewModel.ReportFrame.SourceURL = WebPathHelper.MapUrlFromRoot(
string.Format("Reporting/ResultSummary.aspx?beginDate={0}&endDate={1}&Id={2}&viewType={3}&cTypeValue={4}&cType={5}",
resultSummaryViewModel.BeginDate,
resultSummaryViewModel.EndDate,
viewValue,viewType,
cTypeValue,cType));
If there is another way to get back selected items from lists that would be great also. Thanks.
I had to encode my selection before passing it in the url as so :
string caseType = null;
if (!String.IsNullOrEmpty(viewModel.CaseTypeValue))
{
caseType = HttpUtility.UrlEncode(viewModel.CaseTypeValue, System.Text.Encoding.Default);
}
that worked well for me from there

Categories

Resources