How to get selected dynamic checkbox in xamarin android - c#

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
}
}
}
}
}

Related

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 an image to display in Picturbox from a Listbox selected item

Everything works fine until I actually call the SetPicture() Method. Any ideas as to why the image will not display when the selected item is changed. Right now i only have one image preset until i figure out my problem. Thanks for any help
namespace CelestialWindowsApp
{
public partial class Form1 : Form
{
public static List CelestialLibrary = new List(); private static CelestialBody celestialBody; private static string name; private static string description; private static string image; public static CelestialBody NewPlanet { get { return celestialBody; } set { celestialBody = value; } }
public Form1()
{
InitializeComponent();
PopulateLibrary();
}
public void PopulateLibrary()//Runs when the Form 1 is loaded. Adds preset item into the ListNox.
{
CelestialLibrary = new List<CelestialBody>();
CelestialBody cb1 = new CelestialBody("Earth", "Our Home", #"C:\Users\Cassidy\documents\visual studio 2015\Projects\CelestialWindowsApp\CelestialWindowsApp\ImageResources\earthimage.jpg");
CelestialBody cb2 = new CelestialBody("Mars", "4th planet from the sun.");
CelestialBody cb3 = new CelestialBody("Venus", "2nd planet from the son");
CelestialLibrary.Add(cb1);
CelestialLibrary.Add(cb3);
lbLibrary.DataSource = CelestialLibrary;
foreach (var p in CelestialLibrary)
{
lbLibrary.DisplayMember = "ShowBodies";
}
}
public void AddItem() // Adds the new Item to my library and then adds to and updates the ListBox;
{
CelestialBody cb;
name = txtboxName.Text;
description = txtboxDescription.Text;
image = txtboxImagePath.Text;
cb = new CelestialBody(name, description, image);
CelestialLibrary.Add(cb);
MessageBox.Show(name + " has been added to the Library.");
txtboxName.Text = null;
txtboxDescription.Text = null;
lbLibrary.DataSource = null;
lbLibrary.DataSource = CelestialLibrary;
lbLibrary.DisplayMember = "ShowBodies";
}
public void DisplayItemInfo()//Displays the current selected item information.
{
List<CelestialBody> bodyList = (List<CelestialBody>)lbLibrary.DataSource;
CelestialBody currentItem = bodyList[lbLibrary.SelectedIndex];
foreach (CelestialBody cb in bodyList)
{
if (currentItem.MyId == cb.MyId)
celestialBody = new CelestialBody(cb.Name, cb.Description, cb.ImagePath);
{
txtboxItemInfo.Text = celestialBody.Description;
SetPicture(celestialBody.ImagePath);
}
}
}
public void SetPicture(string image)
{
if (picboxBodyImage.Image != null)
{
picboxBodyImage.Image.Dispose();
}
picboxBodyImage.ImageLocation = image;
}
private void btnAddNewBody_Click(object sender, EventArgs e)
{
AddItem();
}
private void lbLibrary_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayItemInfo();
}
}
}
Did you check the path in variable image. Assuming path is correct, Try below
picboxBodyImage.Image = Image.FromFile(image);

Initialize of a Class as variable in 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

How do I populate the listbox plugin item Name as it is set in the Plugin interface?

When the plugin buttons get loaded, the button gets populated with the name of the IPlugin Interface as it asks in the method
string Name { get; }
I’m trying to get the listbox item to populate with the name the same way its doing so for the button.
private void AssembleComponents
private void AssembleComponents(object sender)
{
ICollection<IPlugin> plugins = GenericPluginLoader<IPlugin>.LoadPlugins("Plugins");
string selection = "";
if (sender is ListBox)
{
if (((ListBox)sender).SelectedValue != null)
selection = ((ListBox)sender).SelectedValue.ToString();
}
string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
DirectoryCatalog cat = new DirectoryCatalog(path);
//ICollection<IPlugin> plugins = PluginLoader.LoadPlugins("Plugins");
foreach (var item in plugins)
{
//add only if not already present
if (!_Plugins.ContainsKey(item.Name))
{
string dllName = GetDLLName(item.Name);
Button b = new Button()
{
Name = dllName.Replace(".", "").ToUpper(),
Content = item.Name,
Visibility = System.Windows.Visibility.Hidden
};
b.Click += b_Click;
PluginGrid.Children.Add(b);
_Plugins.Add(item.Name, item);
// this.PluginGrid.Children.Clear();
//by Vasey
}
}
// make visible the selected plugin button
foreach (var ctl in PluginGrid.Children)
{
if (ctl is Button)
{
Button button = (Button)ctl;
if (button.Name.Equals(selection.Replace(".", "").ToUpper()))
{
button.Visibility = System.Windows.Visibility.Visible;
}
else
{
button.Visibility = System.Windows.Visibility.Hidden;
}
}
}
}
string GetDLLName
string GetDLLName(string Name)
{
string ret = "";
Name = Name.Replace(" ", ""); // strip spaces
Assembly asm = AppDomain.CurrentDomain.GetAssemblies().
SingleOrDefault(assembly => assembly.GetName().Name == Name);
if (asm != null)
{
ret = Path.GetFileNameWithoutExtension(asm.Location);
}
return ret;
}
private void lbFiles_SelectionChanged
private void lbFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
AssembleComponents(sender);
}
How can I implement this?

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