Initialize of a Class as variable in c# - c#

I couldn't understand this code. Why i need to initialize a class as variable Like "private InvoiceMaster _invoiceMaster" And "InvoiceMaster im = new InvoiceMaster()". Please Help me in details. I need to very clear understand.
namespace AHS.Invoice.UI
{
public partial class ReRouteDetail : BasePage
{
#region Declaration
private InvoiceMaster _invoiceMaster;
DataSet _ds = new DataSet();
InvoiceMasterCollection _invoiceMasterCollection = new InvoiceMasterCollection();
#endregion
#region Page Events
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
}
this.LoadColumns();
this.LoadGridData();
}
#endregion
#region Methods
private void LoadGridData()
{
if (base.CurrentScreen.ID == 3780)
{
_ds = new InvoiceMasterCollection().LoadReRouteData();
gc.GridDataSource = _ds;
gc.GridDataBind();
}
else if (base.CurrentScreen.ID == 3781)
{
_ds = new InvoiceMasterCollection().LoadReRouteFromServiceApproverData();
gc.GridDataSource = _ds;
gc.GridDataBind();
}
else if (base.CurrentScreen.ID == 3782)
{
_ds = new InvoiceMasterCollection().LoadReRouteFromServiceConfirmationData();
gc.GridDataSource = _ds;
gc.GridDataBind();
}
}
#endregion
#region Events
protected void gc_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlStatus = e.Row.Cells[7].FindControl("ddlStatus") as DropDownList;
ddlStatus.CssClass = "ReRouteddlStatus";
if (base.CurrentScreen.ID == 3780)
{
DataSet reRouteDataSet = new InvoiceMasterCollection().LoadStatus(Convert.ToInt32(e.Row.Cells[4].Text));
ddlStatus.DataTextField = "Description";
ddlStatus.DataValueField = "ID";
ddlStatus.DataSource = reRouteDataSet;
ddlStatus.DataBind();
}
if (base.CurrentScreen.ID == 3781 || base.CurrentScreen.ID == 3782)
{
ddlStatus.Enabled = false;
}
System.Web.UI.WebControls.Button btnReRoute = e.Row.Cells[8].FindControl("btnReRoute") as System.Web.UI.WebControls.Button;
btnReRoute.CssClass = "btnBackToReRoute";
//Button btnReRoute = e.Row.Cells[8].FindControl("btnReRoute") as Button;
btnReRoute.CommandName = "ReRoute";
btnReRoute.CommandArgument = e.Row.Cells[0].Text;
e.Row.Cells[8].Controls.Add(btnReRoute);
}
}
protected void gc_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ReRoute")
{
int masterID = Convert.ToInt32(e.CommandArgument);
Button button = null;
foreach (GridViewRow rows in gc.GridRows)
{
InvoiceMaster im = new InvoiceMaster();
im.ID = masterID;
// this.LoadGridData();
_invoiceMaster = new InvoiceMaster();
_invoiceMaster = im.GetData();
int id = Convert.ToInt32(rows.Cells[0].Text);
if (id == masterID)
{
button = rows.FindControl("btnReRoute") as Button;
DropDownList ddlStatus(DropDownList)rows.Cells[6].FindControl("ddlStatus");
if (base.CurrentScreen.ID == 3780)
{
_invoiceMaster.StatusID = Convert.ToInt32(ddlStatus.SelectedItem.Value);
}
if (base.CurrentScreen.ID == 3781)
{
_invoiceMaster.StatusID = 13;
}
if (base.CurrentScreen.ID == 3782)
{
_invoiceMaster.StatusID = 11;
}
_invoiceMaster.Save();
break;
}
}
LoadColumns();
LoadGridData();
base.ShowClientMessage("Invoice Backed Successfully.");
}
}
#endregion
}
}

When you write this line:
private InvoiceMaster _invoiceMaster;
you are just defining a private member of the class of type InvoiceMaster. At this point however the reference is pointing to nothing (the "value" is null).
In this line:
InvoiceMaster im = new InvoiceMaster();
you are also creating a private member of the class (the default in c# is private) and this time you are assigning to that reference a new object that you are creating.
The following lines will not compile and must be in a scope of a function:
im.ID = masterID;
_invoiceMaster = new InvoiceMaster();
_invoiceMaster = im.GetData();
I recommend that you go through one of the many tutorial out there to better understand about data types, variables and scopes

Related

Xamarin forms Combobox:SFComboBox!! How i can refresh my combobox?

I'm trying to use CollectionChanged.
My code:
public List<RSSNotification> Notificacoes { get; private set; }
public RSSReader rssreader;
public List<RSSReader> feedsAdicionados = new List<RSSReader>();
ObservableCollection<string> comboFeeds = new ObservableCollection<string>();
public ThirdPage(List<RSSReader> feed, List<RSSNotification> Not)
{
InitializeComponent();
mycombobox.ItemsSource = ComboFeeds;
ComboFeeds.Clear();
Notificacoes = Not;
feedsAdicionados = feed;
for (int i = 0; i < feedsAdicionados.Count; i++)
{
if (feedsAdicionados[i] != null) ComboFeeds.Add(feedsAdicionados[i].title);
}
}
private async void ButtonAdicionar_Clicked(object sender, EventArgs e)
{
rssreader = new RSSReader();
PopUp1 Pop = new PopUp1(0, rssreader, feedsAdicionados, Notificacoes);
await Navigation.ShowPopupAsync(Pop);
await DisplayAlert("Sucesso", "Feed Adicionado com sucesso", "Ok" );
Notificacoes = Pop.Notificacoes;
rssreader = Pop.RSS;
ComboFeeds.Add(rssreader.title);
this.ComboFeeds.CollectionChanged += ComboFeeds_CollectionChanged;
}
private void ComboFeeds_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
}
When the popup ends, I add it to my combobox via a class, then try to update, but it doesn't work.
Thx for all help

change textbox value if i change combobox value

i will try autoload textbox value if i change my combobox
this is my form
this is my repositories
AreaRepository
public string GetAreaNamebyAreaID(int areaID)
{
var result = db.btbArea.SingleOrDefault(g => g.AreaID == areaID);
if (result == null)
return string.Empty;
return result.AreaName;
}
HowzehRepository
public string GetHowzehNamebyHoezehID(int howzehID)
{
var result = db.btbHowzeh.SingleOrDefault(g => g.HowzehID == howzehID);
if (result == null)
return string.Empty;
return result.HowzehName;
}
PaygahRepository
public string GetPaygahNamebyPaygahID(int paygahID)
{
var result = db.btbPaygah.SingleOrDefault(g => g.PaygahID == paygahID);
if (result == null)
return string.Empty;
return result.PaygahName;
}
i will try load my textbox value if i change my combobox index
private void frmAreasManage_Load(object sender, EventArgs e)
{
//Load AreaComboBox Source from AreaTable
using (UnitOfWork db = new UnitOfWork())
{
cmbAreaNumber.DataSource = db.AreaRepository.Get();
cmbAreaNumber.DisplayMember = "AreaNumber";
cmbAreaNumber.ValueMember = "AreaID";
}
}
private void cmbAreaNumber_SelectedIndexChanged(object sender, EventArgs e)
{
cmbAreaNumber.SelectedIndex = 0;
string selectedValue = cmbAreaNumber.SelectedValue.ToString();
using (UnitOfWork db = new UnitOfWork())
if (!string.IsNullOrEmpty(selectedValue))
{
{
//Load HowzehhComboBox From HowzehTable Filter By AreaID
cmbHowzehNumber.DataSource = db.HowzehRepository.GetNameIDByFilter(selectedValue);
cmbHowzehNumber.DisplayMember = "HowzehNumber";
cmbHowzehNumber.ValueMember = "HowzehID";
//Get AreaName from AreaTable Filter By AreaID
txtAreaName.Text = db.AreaRepository.GetAreaNamebyAreaID(Convert.ToInt32(cmbAreaNumber.SelectedValue));
}
}
}
private void cmbHowzehNumber_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = cmbHowzehNumber.SelectedValue.ToString();
using (UnitOfWork db = new UnitOfWork())
if (!string.IsNullOrEmpty(selectedValue))
{
//Load PaygahComboBox From PaygahTable Filter By HowzehID
cmbPaygahNumber.DataSource = db.PaygahRepository.GetNameIDByFilter(selectedValue);
cmbPaygahNumber.DisplayMember = "PaygahNumber";
cmbPaygahNumber.ValueMember = "PaygahID";
//Get HowzehName from HowzehTable Filter By HowzehID
txtHowzehName.Text = db.HowzehRepository.GetHowzehNamebyHoezehID(Convert.ToInt32(selectedValue));
}
}
private void cmbPaygahNumber_SelectedIndexChanged(object sender, EventArgs e)
{
using (UnitOfWork db = new UnitOfWork())
{
//Get HowzehName from HowzehTable Filter By HowzehID
txtPaygahName.Text = db.PaygahRepository.GetPaygahNamebyPaygahID(Convert.ToInt32(selectedValue));
}
}
}
after i start my code i recieve this error
i handle my null and if i ignore this line everything is fine !
This Code Solve My Problem ( Always if i Find Way for solved My Problem I Answer My Question For Help Other Guys )
private void frmAreasManage_Load(object sender, EventArgs e)
{
//Load AreaComboBox Source from AreaTable
using (UnitOfWork db = new UnitOfWork())
{
// At first assign properties DisplayMember and ValueMember.
cmbAreaNumber.DisplayMember = "AreaNumber";
cmbAreaNumber.ValueMember = "AreaID";
// And then assign DataSource property of the cmbLayerName.
cmbAreaNumber.DataSource = db.AreaRepository.Get();
}
}
private void cmbAreaNumber_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = cmbAreaNumber.SelectedValue.ToString();
using (UnitOfWork db = new UnitOfWork())
if (!string.IsNullOrEmpty(selectedValue))
{
/// At first assign properties DisplayMember and ValueMember.
cmbHowzehNumber.DisplayMember = "HowzehNumber";
cmbHowzehNumber.ValueMember = "HowzehID";
// And then assign DataSource property of the cmbHowzehNumber.
cmbHowzehNumber.DataSource = db.HowzehRepository.GetNameIDByFilter(selectedValue);
//Get AreaName from AreaTable Filter By AreaID
txtAreaName.Text = db.AreaRepository.GetAreaNamebyAreaID(Convert.ToInt32(selectedValue));
}
}
private void cmbHowzehNumber_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = cmbHowzehNumber.SelectedValue.ToString();
using (UnitOfWork db = new UnitOfWork())
if (!string.IsNullOrEmpty(selectedValue))
{
//Load PaygahComboBox From PaygahTable Filter By HowzehID
cmbPaygahNumber.DataSource = db.PaygahRepository.GetNameIDByFilter(selectedValue);
cmbPaygahNumber.DisplayMember = "PaygahNumber";
cmbPaygahNumber.ValueMember = "PaygahID";
//Get HowzehName from HowzehTable Filter By HowzehID
txtHowzehName.Text = db.HowzehRepository.GetHowzehNamebyHoezehID(Convert.ToInt32(selectedValue));
}
}
private void cmbPaygahNumber_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedValue = cmbHowzehNumber.SelectedValue.ToString();
using (UnitOfWork db = new UnitOfWork())
{
//Get HowzehName from HowzehTable Filter By HowzehID
txtPaygahName.Text = db.PaygahRepository.GetPaygahNamebyPaygahID(Convert.ToInt32(selectedValue));
}
}

use variables from a class in other classes

I create a class that I define some variables with their properties.
also I have two class "Form1" and "Form2".
I assign values to this variables in "Form1" but when I want to use the values in "Form2" after I assigned them and show them through MessageBox.Show(), I find out the variables are empty.
class Property
{
private string a_username;
private string a_email;
public string username
{
get { return a_username; }
set { a_username = value; }
}
public string email
{
get { return a_email; }
set { a_email = value; }
}
public string password { get; set; } = "88306540";
}
the assignment: (this function is in "Form1")
Property pro = new Property();
private void CreateUserInform()
{
userid = File.ReadLines(filePath).Skip(idx).Take(1).First();
// MessageBox.Show(userid);
HtmlElementCollection elemcol = webBrowser2.Document.GetElementsByTagName("option");
int i = 0;
string[] mailservices = new string[elemcol.Count];
foreach (HtmlElement elem in elemcol)
{
mailservices[i] = elem.InnerText;
i += 1;
}
pro.username = userid;
Random rand = new Random();
mailservice = mailservices[rand.Next(10)];
pro.email = pro.username + mailservice;
wb2func_create_mail();
}
call function: (this function is in "Form2" and it called after previous function.)
Property pro = new Property();
public void signup_fill()
{
HtmlElementCollection elemcol = site.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elemcol)
{
if (elem.Name == "login")
elem.SetAttribute("value", pro.username);
if (elem.Name == "remail")
elem.SetAttribute("value", pro.email);
if (elem.Name == "password")
elem.SetAttribute("value", pro.password);
if (elem.Name == "password2")
elem.SetAttribute("value", pro.password);
}
MessageBox.Show(pro.username);
}
I should mention that the "password" variable was shown pretty good but the others were shown empty.
also when I call them in "Form1" that I used to define them, it works just fine and shows the correct assignment.
the completely Form2 codes:
namespace Bypassing
{
public partial class Form2 : Form
{
string referal_link;
Property pro = new Property();
public Form2(Property form1Property)
{
InitializeComponent();
pro = form1Property;
}
public void signup_fill()
{
HtmlElementCollection elemcol = site.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elemcol)
{
if (elem.Name == "login")
elem.SetAttribute("value", pro.username);
if (elem.Name == "remail")
elem.SetAttribute("value", pro.email);
if (elem.Name == "password")
elem.SetAttribute("value", pro.password);
if (elem.Name == "password2")
elem.SetAttribute("value", pro.password);
}
MessageBox.Show(pro.username);
}
private void btn_fill_Click(object sender, EventArgs e)
{
signup_fill();
}
private void btn_logout_Click(object sender, EventArgs e)
{
HtmlElementCollection elemcol = site.Document.GetElementsByTagName("a");
foreach (HtmlElement elem in elemcol)
{
if (elem.InnerText == " Log out ")
elem.InvokeMember("click");
}
}
private void btn_next_link_Click(object sender, EventArgs e)
{
}
public bool btn_fill_enabled
{
get { return btn_fill.Enabled; }
set { btn_fill.Enabled = value; }
}
public bool btn_logout_enabled
{
get { return btn_logout.Enabled; }
set { btn_logout.Enabled = value; }
}
public bool btn_next_link_enabled
{
get { return btn_next_link.Enabled; }
set { btn_next_link.Enabled = value; }
}
private void avelon_site_Completed(object sender, WebBrowserNavigatedEventArgs e)
{
Form1 main_win = new Form1();
main_win.text_edit();
}
}
}
Form1 codes:
namespace BitcoinCloudMiningBypassApp
{
public partial class Form1 : Form
{
private string mailservice;
private string userid;
int idx = 29;
bool wb1flag = true;
bool wb2flag = true;
bool wb1ready = false;
bool wb2ready = false;
bool workflag = false;
bool start = false;
string filePath;
//StreamWriter file2 = new StreamWriter("avelon_users_email.txt", true);
//StreamWriter file = new StreamWriter("avelon_referal_links.txt", true);
Property pro = new Property();
private void OpenFileDialogForImportingUserId()
{
//var fileContent = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "C:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
btn_start.Enabled = true;
////Read the contents of the file into a stream
//var fileStream = openFileDialog.OpenFile();
//using (StreamReader reader = new StreamReader(fileStream))
//{
// fileContent = reader.ReadToEnd();
//}
}
}
}
private void CreateUserInform()
{
userid = File.ReadLines(filePath).Skip(idx).Take(1).First();
// MessageBox.Show(userid);
HtmlElementCollection elemcol = webBrowser2.Document.GetElementsByTagName("option");
int i = 0;
string[] mailservices = new string[elemcol.Count];
foreach (HtmlElement elem in elemcol)
{
mailservices[i] = elem.InnerText;
i += 1;
}
pro.username = userid;
Random rand = new Random();
mailservice = mailservices[rand.Next(10)];
pro.email = pro.username + mailservice;
//MessageBox.Show(avelon_email);
wb2func_create_mail();
}
public Form1()
{
InitializeComponent();
webBrowser2.Navigate("https://temp-mail.org/en/option/change/");
}
private void btn_start_Click(object sender, EventArgs e)
{
Form2 avelon = new Form2(pro);
avelon.Show();
//VPN vpn = new VPN();
// MessageBox.Show(vpn.ConnectVPN(vpn.SetServer(0)).ToString());
CreateAvelonUserInform();
start = true;
btn_load.Enabled = false;
btn_start.Enabled = false;
avelon.btn_logout_enabled = true;
btn_refresh.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
btn_load.Enabled = false;
btn_start.Enabled = false;
btn_next.Enabled = false;
//Process.Start("cmd.exe", "taskkill / F / im notepad.exe");
}
private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (wb2flag)
{
wb2flag = false;
wb2ready = true;
if (!start)
btn_load.Enabled = wb2ready;
}
else
{
text_edit();
}
}
private void wb2func_create_mail()
{
HtmlElementCollection elemcol = webBrowser2.Document.GetElementsByTagName("option");
foreach (HtmlElement elem in elemcol)
{
if (elem.InnerText == mailservice)
elem.SetAttribute("selected", "selected");
}
HtmlElementCollection elemcol2 = webBrowser2.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elemcol2)
if (elem.GetAttribute("name") == "mail")
elem.SetAttribute("value", pro.username);
//wb2flag = true;
//workflag = true;
webBrowser2.Document.GetElementById("postbut").InvokeMember("click");
}
private void btn_load_Click(object sender, EventArgs e)
{
//OpenFileDialogForImportingUserId();
VPN vpn = new VPN();
MessageBox.Show(vpn.ConnectVPN(vpn.SetServer(0)).ToString());
//Process.Start("C:\\Users\\Hossein\\Desktop\\output.bat");
//MessageBox.Show(Environment.GetEnvironmentVariable("a", EnvironmentVariableTarget.Process));
//MessageBox.Show(Environment.GetEnvironmentVariable("a", EnvironmentVariableTarget.User));
//MessageBox.Show(Environment.GetEnvironmentVariable("a", EnvironmentVariableTarget.Machine));
}
public void text_edit()
{
txt_username.TextChanged += new EventHandler(text_change);
txt_username.Text = pro.username;
txt_email.Text = pro.email;
}
private void btn_next_Click(object sender, EventArgs e)
{
}
private void btn_refresh_Click(object sender, EventArgs e)
{
webBrowser2.Navigate("https://temp-mail.org/en/option/change/");
}
private void text_change(object s , EventArgs e)
{
Form2 avelon = new Form2(pro);
avelon.btn_fill_enabled = true;
}
}
}
Seems that password is showing fine as it's defined at the Property class itself so, each time you create a new object of that class, it will be setted by default untill you change it.
The reason you don't see the data from Form 1 at Form 2 seems to be that you aren't passing the Property object from Form 1 to Form 2, so you have a Property object filled with data at Form 1 but at Form 2 you remain with a newly created Property object. Just modify the Form 2 constructor so it accepts a Property parameter and pass it from Form 1.
Example (this goes on your Form2's code):
public Form2 (Property form1Property){
InitializeComponent();
pro = form1Property;
}
That creates a code that executes each time you create a new Form2 and requires you to pass a Property object to create it (new Form2(pro); in Form1) so it assigns Form2's Property object to the one you passed when creating it's object on Form1.
Also make your Property class public, so you can use it as a parameter at Form2's constructor.
More info about constructors here
Hope this helps you!
P.S: Looking at your code I see that you're creating a global Form2 object. You should create it at btn_start_Click before you are showing it, so data is filled up correctly (when you show it your Form1's Property object is filled, now when you create it it's not filled)

How to get selected dynamic checkbox in xamarin android

Here is my code, how to get selected checkbox from this code.
1st..i get file name from sqlite and loop it to dynamic checkbox.
private void DisplayData()
{
fileList = GeneralFunc.GetAllFile();
var checkBoxes = new CheckBox[0];
for (int i = 0; i < fileList.Count(); i++)
{
var checkBox = new CheckBox(this);
checkBox.Text = fileList[i].ST_filename;
checkBox.Id = i;
checkBox.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
linearLayoutClear.AddView(checkBox);
Array.Resize(ref checkBoxes, i + 1);
checkBoxes[i] = checkBox;
}
}
private class CheckedChangeListener : Java.Lang.Object, CompoundButton.IOnCheckedChangeListener //checkedChangeListener
{
private Activity activity;
public CheckedChangeListener(Activity activity)
{
this.activity = activity;
}
public void OnCheckedChanged(CompoundButton buttonView, bool isChecked) //check checked checkbox
{
string test = buttonView.Id.ToString();
string checkedName = null;
List<string> selectedFileList = new List<string>();
if (isChecked)
{
checkedName = buttonView.Text;
selectedFileList.Add(checkedName); //get selected checkbox put in list
}
else
{
selectedFileList.Remove(checkedName);
}
}
}
kindly help me.
my code like this..pls help me.
try to get selected checkbox and put to list.
Checkbox in Xamarin has a property called Checked. Does not have the same methods to set it to checked or check if it is checked as in Java.
// Reverse checked
if (checkbox.Checked)
{
checkbox.Checked = false;
}
else
{
checkbox.Checked = true;
}
You can also loop through checkboxes:
var checkboxList = new List<CheckBox>();
//Create new instance of checkbox
//var checkbox = new CheckBox();
checkboxList.Add(checkbox);
//Loop
foreach (var checkbox in checkboxList)
{
checkbox.Checked = true;
}
EDIT
As per the question in the comment:
how about i use. checkBoxes[i].CheckedChange += CheckedControl;
private void CheckedControl(object sender, EventArgs e) { //do thing here }
You would then check if sender is a checkbox:
protected void CheckedControl(object sender, EventArgs e)
{
if (sender is CheckBox)
{
var checkbox = (CheckBox)sender;
if (checkbox.Checked)
{
// It is checked
}
//Change the checked status
checkbox.Checked = true;
}
}
EDIT 2
my code can me like this ?
public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
{
string test = buttonView.Id.ToString();
List<string> selectedFileList = new List<string>();
if (isChecked)
{
string checkedName = buttonView.Text;
selectedFileList.Add(checkedName);
}
}
You can add the CheckedChange to CheckedControl and call OnCheckedChanged from within:
protected void CheckedControl(object sender, EventArgs e)
{
if (sender is CheckBox)
{
var checkbox = (CheckBox)sender;
OnCheckedChanged(checkbox);
}
}
Then in your OnCheckedChanged you have List<string> selectedFileList - I would move that out of the method into the class private List<string> selectedFileList
Your method will end up looking like this:
public void OnCheckedChanged(CheckBox checkbox)
{
if (selectedFileList == null)
{
selectedFileList = new List<string>();
}
string test = checkbox.Id.ToString();
string checkedName = checkbox.Text;
if (checkbox.Checked)
{
selectedFileList.Add(checkedName);
}
else
{
selectedFileList.Remove(checkedName);
}
}
WORKING CODE
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using System.Collections.Generic;
namespace App1
{
[Activity(MainLauncher = true)]
public class MainActivity : Activity
{
private LinearLayout linearLayoutClear;
//private CheckBox[] checkBoxes;
private List<string> selectedFileList;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
linearLayoutClear = FindViewById<LinearLayout>(Resource.Id.linearLayoutClear);
DisplayData();
btnGetAllChecked = FindViewById<Button>(Resource.Id.btnGetAllChecked);
btnGetAllChecked.Click += (s, e) =>
{
if(selectedFileList != null)
{
Android.Util.Log.Debug("App.MainActivity", "AllChecked: " + string.Join(", ", selectedFileList));
}
};
}
private void DisplayData()
{
var fileList = GeneralFunc.GetAllFile();
//checkBoxes = new CheckBox[0];
for (int i = 0; i < fileList.Count(); i++)
{
var checkBox = new CheckBox(this);
checkBox.Text = fileList[i].ST_filename;
checkBox.Id = i;
checkBox.LayoutParameters = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
checkBox.CheckedChange += CheckBox_CheckedChange;
//Array.Resize(ref checkBoxes, i + 1);
//checkBoxes[i] = checkBox;
linearLayoutClear.AddView(checkBox);
}
}
private void CheckBox_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
{
if (sender is CheckBox)
{
var checkbox = (CheckBox)sender;
string test = checkbox.Id.ToString();
string checkedName = checkbox.Text;
if (selectedFileList == null)
{
selectedFileList = new List<string>();
}
if (checkbox.Checked)
{
selectedFileList.Add(checkedName); //get selected checkbox put in list
}
else
{
selectedFileList.Remove(checkedName); //checkbox is not checked anymore so remove it from the list
}
}
}
}
}

how to check multiple row in DevExpress CheckEdit

This is my code
gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn()
{
Caption = "Selected",
ColumnEdit = new RepositoryItemCheckEdit() { },
VisibleIndex = 1,
UnboundType = DevExpress.Data.UnboundColumnType.Boolean
});
But I cant check multiple checkEdit at the same time.
Why was that?
And please show me the way out.
Thanks.
Well, there are two answers to that question, one very simple, and one very complex, let's start with the simple:
If you want to have an column that has the "Selected" caption and act as a checkbox to indicate that a particular record was selected, you have two options:
1) If you can alter the class in your data source to add a property that is bool and could be used with DataBinding, then, all is done in a very simple way, jast add the property and bind the data and it will work:
class SimplePerson
{
public string Name { get; set; }
public bool IsSelected { get; set; }
}
BindingList<SimplePerson> source = new BindingList<SimplePerson>();
void InitGrid()
{
source.Add(new SimplePerson() { Name = "John", IsSelected = false });
source.Add(new SimplePerson() { Name = "Gabriel", IsSelected = true });
gridControl.DataSource = source;
}
2) You cannot alter you classes, so you need to this by signing the correct grid events and drawing the column yourself, and also adding the right handlers for all the actions.... is a very complex case, but for your luck i have this done, because i have had this problem in the past, so i will post you my full class!
public class GridCheckMarksSelection
{
public event EventHandler SelectionChanged;
protected GridView _view;
protected ArrayList _selection;
private GridColumn _column;
private RepositoryItemCheckEdit _edit;
public GridView View
{
get { return _view; }
set
{
if (_view == value)
return;
if (_view != null)
Detach();
_view = value;
Attach();
}
}
public GridColumn CheckMarkColumn { get { return _column; } }
public int SelectedCount { get { return _selection.Count; } }
public GridCheckMarksSelection()
{
_selection = new ArrayList();
}
public GridCheckMarksSelection(GridView view)
: this()
{
this.View = view;
}
protected virtual void Attach()
{
if (View == null)
return;
_selection.Clear();
_view = View;
_edit = View.GridControl.RepositoryItems.Add("CheckEdit")
as RepositoryItemCheckEdit;
_edit.EditValueChanged += edit_EditValueChanged;
_column = View.Columns.Insert(0);
_column.OptionsColumn.AllowSort = DefaultBoolean.False;
_column.VisibleIndex = int.MinValue;
_column.FieldName = "CheckMarkSelection";
_column.Caption = "Mark";
_column.OptionsColumn.ShowCaption = false;
_column.UnboundType = UnboundColumnType.Boolean;
_column.ColumnEdit = _edit;
View.CustomDrawColumnHeader += View_CustomDrawColumnHeader;
View.CustomDrawGroupRow += View_CustomDrawGroupRow;
View.CustomUnboundColumnData += view_CustomUnboundColumnData;
View.MouseUp += view_MouseUp;
}
protected virtual void Detach()
{
if (_view == null)
return;
if (_column != null)
_column.Dispose();
if (_edit != null)
{
_view.GridControl.RepositoryItems.Remove(_edit);
_edit.Dispose();
}
_view.CustomDrawColumnHeader -= View_CustomDrawColumnHeader;
_view.CustomDrawGroupRow -= View_CustomDrawGroupRow;
_view.CustomUnboundColumnData -= view_CustomUnboundColumnData;
_view.MouseDown -= view_MouseUp;
_view = null;
}
protected virtual void OnSelectionChanged(EventArgs e)
{
if (SelectionChanged != null)
SelectionChanged(this, e);
}
protected void DrawCheckBox(Graphics g, Rectangle r, bool Checked)
{
var info = _edit.CreateViewInfo() as CheckEditViewInfo;
var painter = _edit.CreatePainter() as CheckEditPainter;
ControlGraphicsInfoArgs args;
info.EditValue = Checked;
info.Bounds = r;
info.CalcViewInfo(g);
args = new ControlGraphicsInfoArgs(info, new GraphicsCache(g), r);
painter.Draw(args);
args.Cache.Dispose();
}
private void view_MouseUp(object sender, MouseEventArgs e)
{
if (e.Clicks == 1 && e.Button == MouseButtons.Left)
{
GridHitInfo info;
var pt = _view.GridControl.PointToClient(Control.MousePosition);
info = _view.CalcHitInfo(pt);
if (info.InRow && _view.IsDataRow(info.RowHandle))
UpdateSelection();
if (info.InColumn && info.Column == _column)
{
if (SelectedCount == _view.DataRowCount)
ClearSelection();
else
SelectAll();
}
if (info.InRow && _view.IsGroupRow(info.RowHandle)
&& info.HitTest != GridHitTest.RowGroupButton)
{
bool selected = IsGroupRowSelected(info.RowHandle);
SelectGroup(info.RowHandle, !selected);
}
}
}
private void View_CustomDrawColumnHeader
(object sender, ColumnHeaderCustomDrawEventArgs e)
{
if (e.Column != _column)
return;
e.Info.InnerElements.Clear();
e.Painter.DrawObject(e.Info);
DrawCheckBox(e.Graphics, e.Bounds, SelectedCount == _view.DataRowCount);
e.Handled = true;
}
private void View_CustomDrawGroupRow
(object sender, RowObjectCustomDrawEventArgs e)
{
var info = e.Info as GridGroupRowInfo;
info.GroupText = " " + info.GroupText.TrimStart();
e.Info.Paint.FillRectangle
(e.Graphics, e.Appearance.GetBackBrush(e.Cache), e.Bounds);
e.Painter.DrawObject(e.Info);
var r = info.ButtonBounds;
r.Offset(r.Width * 2, 0);
DrawCheckBox(e.Graphics, r, IsGroupRowSelected(e.RowHandle));
e.Handled = true;
}
private void view_CustomUnboundColumnData
(object sender, CustomColumnDataEventArgs e)
{
if (e.Column != CheckMarkColumn)
return;
if (e.IsGetData)
e.Value = IsRowSelected(View.GetRowHandle(e.ListSourceRowIndex));
else
SelectRow(View.GetRowHandle(e.ListSourceRowIndex), (bool)e.Value);
}
private void edit_EditValueChanged(object sender, EventArgs e)
{
_view.PostEditor();
}
private void SelectRow(int rowHandle, bool select, bool invalidate)
{
if (IsRowSelected(rowHandle) == select)
return;
object row = _view.GetRow(rowHandle);
if (select)
_selection.Add(row);
else
_selection.Remove(row);
if (invalidate)
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
public object GetSelectedRow(int index)
{
return _selection[index];
}
public int GetSelectedIndex(object row)
{
return _selection.IndexOf(row);
}
public void ClearSelection()
{
_selection.Clear();
View.ClearSelection();
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
private void Invalidate()
{
_view.CloseEditor();
_view.BeginUpdate();
_view.EndUpdate();
}
public void SelectAll()
{
_selection.Clear();
var dataSource = _view.DataSource as ICollection;
if (dataSource != null && dataSource.Count == _view.DataRowCount)
_selection.AddRange(dataSource); // fast
else
for (int i = 0; i < _view.DataRowCount; i++) // slow
_selection.Add(_view.GetRow(i));
Invalidate();
OnSelectionChanged(EventArgs.Empty);
}
public void SelectGroup(int rowHandle, bool select)
{
if (IsGroupRowSelected(rowHandle) && select) return;
for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
{
int childRowHandle = _view.GetChildRowHandle(rowHandle, i);
if (_view.IsGroupRow(childRowHandle))
SelectGroup(childRowHandle, select);
else
SelectRow(childRowHandle, select, false);
}
Invalidate();
}
public void SelectRow(int rowHandle, bool select)
{
SelectRow(rowHandle, select, true);
}
public bool IsGroupRowSelected(int rowHandle)
{
for (int i = 0; i < _view.GetChildRowCount(rowHandle); i++)
{
int row = _view.GetChildRowHandle(rowHandle, i);
if (_view.IsGroupRow(row))
if (!IsGroupRowSelected(row))
return false;
else
if (!IsRowSelected(row))
return false;
}
return true;
}
public bool IsRowSelected(int rowHandle)
{
if (_view.IsGroupRow(rowHandle))
return IsGroupRowSelected(rowHandle);
object row = _view.GetRow(rowHandle);
return GetSelectedIndex(row) != -1;
}
public void UpdateSelection()
{
_selection.Clear();
Array.ForEach(View.GetSelectedRows(), item => SelectRow(item, true));
}
}
And now you need to know how to use this:
void InitGrid()
{
gridControl.DataSource = source;
// Do this after the database for the grid is set!
selectionHelper = new GridCheckMarksSelection(gridView1);
// Define where you want the column (0 = first)
selectionHelper.CheckMarkColumn.VisibleIndex = 0;
// You can even subscrive to the event that indicates that
// there was change in the selection.
selectionHelper.SelectionChanged += selectionHelper_SelectionChanged;
}
void selectionHelper_SelectionChanged(object sender, EventArgs e)
{
// Do something when the user selects or unselects something
}
But how do you retrieve all the selected items? There is a example assuming that the type bond is 'Person'
/// <summary>
/// Return all selected persons from the Grid
/// </summary>
public IList<Person> GetItems()
{
var ret = new List<Person>();
Array.ForEach
(
gridView1.GetSelectedRows(),
cell => ret.Add(gridView1.GetRow(cell) as Person)
);
return ret;
}

Categories

Resources