C# datagridview Wrong column index - c#

i've got an event handler for columncontentclicked and it works fine, until i shorten the datalist with stored procedure. after that the indexnum that is return is 0 instead of 5 or 6.
Do i have to refresh datagridview or something?
here's te code
:
int lastcol = dataGridView1.Columns.Count;
// MessageBox.Show(e.ColumnIndex.ToString() + lastcol.ToString());
if (e.ColumnIndex == lastcol - 1)
{
int index = int.Parse(dataGridView1.CurrentRow.Cells[0].Value.ToString());
Global.size = this.Size;
Global.position = this.Location;
Global.overzicht_select = index.ToString();
if (Global.give_return == false)
{
switch(type)
{
case 1:
Global.edit_form_proj = false;
project_form project_form1 = new project_form(this);
project_form1.Show(this);
this.Hide();
break;
case 2:
Global.edit_form_bedr = false;
bedrijf_form bedrijf_form1 = new bedrijf_form(this);
bedrijf_form1.Show(this);
this.Hide();
break;
case 3:
Global.edit_form_pers = false;
persoon_form persoon_form1 = new persoon_form(this);
persoon_form1.Show(this);
this.Hide();
break;
}
}
else
{
Global.return_id = index.ToString();
if (pf != null)
{
pf.fill_id();
}
if (pr != null)
{
pr.fill_id();
}
Global.give_return = false;
Close();
}
}
}
}

I found my problem. the column that I wanted clickable is a buttoncolumn, witch I add when loading the grid. but after filter that column doesnt get refresh or get new data so it things i is the first and only column left whilst the other columns get rebuilt. so calling dataGridView1.Columns.Clear(); and recreating the button column after grid is refilld did the trick, –

Related

ObjectListView - Rows are formatted only after MouseOver on Items

I am in need of some assistance or advice/experience of someone else.
Here is what I'm struggling with:
In my project an objectlistview olvDifference is used to visualize items (Type Conflict) of a list. So far I was able to add the Columns needed and format them properly. But the format provided with
private void ConflictFormatRow(object sender,
BrightIdeasSoftware.FormatRowEventArgs e)
{
Conflict conflict = (Conflict)e.Model;
if (conflict == null) return;
if (conflict.resolution == ConflictResolution.None) e.Item.BackColor = conflictColor;
else if (conflict.resolution == ConflictResolution.UseMine) e.Item.BackColor = mineColor;
else if (conflict.resolution == ConflictResolution.UseTheirs) e.Item.BackColor = theirsColor;
else e.Item.BackColor = System.Drawing.Color.White;
if(e.Model == olvConflictList.SelectedObject)
{
BrightIdeasSoftware.RowBorderDecoration a = new BrightIdeasSoftware.RowBorderDecoration();
a.BorderPen.Color = Color.Black;
a.BorderPen.Width = 3;
a.CornerRounding = 0;
a.FillBrush = Brushes.Transparent;
e.Item.Decoration = a;
}
else
{
BrightIdeasSoftware.RowBorderDecoration b = new BrightIdeasSoftware.RowBorderDecoration();
b.BorderPen.Color = Color.Transparent;
b.BorderPen.Width = 0;
b.CornerRounding = 0;
b.FillBrush = Brushes.Transparent;
e.Item.Decoration = b;
}
}
In the constructor of the form (WFA), the AspectGetter is assigned and the objects to display are set.
Designer-Generated code equals the block below:
//
// olvConflictList
//
this.olvConflictList.AllColumns.Add(this.olvcConflictList);
this.olvConflictList.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.olvConflictList.CellEditUseWholeCell = false;
this.olvConflictList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.olvcConflictList});
this.olvConflictList.Cursor = System.Windows.Forms.Cursors.Default;
this.olvConflictList.FullRowSelect = true;
this.olvConflictList.Location = new System.Drawing.Point(780, 90);
this.olvConflictList.Name = "olvConflictList";
this.olvConflictList.Size = new System.Drawing.Size(286, 489);
this.olvConflictList.TabIndex = 18;
this.olvConflictList.UseCellFormatEvents = true;
this.olvConflictList.UseCompatibleStateImageBehavior = false;
this.olvConflictList.View = System.Windows.Forms.View.Details;
this.olvConflictList.FormatRow += new System.EventHandler<BrightIdeasSoftware.FormatRowEventArgs>(this.ConflictFormatRow);
this.olvConflictList.SelectedIndexChanged += new System.EventHandler(this.olvDifferenceGroups_SelectedIndexChanged);
//
// olvcConflictList
//
this.olvcConflictList.AspectName = "";
this.olvcConflictList.AutoCompleteEditor = false;
this.olvcConflictList.AutoCompleteEditorMode = System.Windows.Forms.AutoCompleteMode.None;
this.olvcConflictList.FillsFreeSpace = true;
this.olvcConflictList.Groupable = false;
this.olvcConflictList.HeaderCheckBoxUpdatesRowCheckBoxes = false;
this.olvcConflictList.Hideable = false;
this.olvcConflictList.IsEditable = false;
this.olvcConflictList.MinimumWidth = 50;
this.olvcConflictList.Searchable = false;
this.olvcConflictList.Sortable = false;
this.olvcConflictList.Text = "Conflicts";
this.olvcConflictList.UseFiltering = false;
this.olvcConflictList.Width = 283;
The only item in the olv has no BackGroundColor (White, default):
After starting the process, it is shown as one can see in the pic above, but I'd expect it to be initialized as in the pic below (after I hovered over it with my mouse the first time).
The only item in the olv has BackGroundColor conflictColor as assigned in the ConflictFormatRow:
Where do I need to improve my code? Any advices?
Well, I could figure it out myself.
I took a look at the source of OLV and what i found out so far:
In my case, the first row, here "Conflicts", was set to "Groupable=False", but the OLV itself was set to "ShowGroups=True".
FormatRow is fired in PostProcessOneRow, which is called according to source (Version: 2.9.1.0) in following logic:
protected virtual void PostProcessRows() {
// If this method is called during a BeginUpdate/EndUpdate pair, changes to the
// Items collection are cached. Getting the Count flushes that cache.
#pragma warning disable 168
// ReSharper disable once UnusedVariable
int count = this.Items.Count;
#pragma warning restore 168
int i = 0;
if (this.ShowGroups) {
foreach (ListViewGroup group in this.Groups) {
foreach (OLVListItem olvi in group.Items) {
this.PostProcessOneRow(olvi.Index, i, olvi);
i++;
}
}
} else {
foreach (OLVListItem olvi in this.Items) {
this.PostProcessOneRow(olvi.Index, i, olvi);
i++;
}
}
}
Since grouping failed, due to no groupable rows being present in OLV, the PostProcessOneRow in the if-body was not hit even once (foreach operated in "this.Groups" whichs count was 0).
Set "ShowGroups=False", works like a charm now.

How to manage different content based on a user role in asp.net C#

I have a structure of different tables in SQL server that allows me to store multiple roles and users (in this case, an User can handle multiple roles).
When I try to turn visible a control in an .aspx depending of the role that the logged-in user has, it gets tired to handle whether to show or not, enable or not the controls that the role should handle.
I already have a solution, but it is hard to maintain. The problem is that the client usually asks for updates from time to time.
What is the best practice to enable controls in .aspx depending on a user role?
An apology for my poor English.
...
...
Every time the client loged-in enter into a .aspx I display different buttons with the roles that he have. For example, if person A have rol 1 and 2 then I display buttons for role 1 and 2. I allow him to choose the role with which he wants to enter the form. If person B have only one rol (for example: rol 3) then I just load the content for rol 3.
protected void accesos()
{
try
{
bool acceso1 = false;
bool acceso2 = false;
bool acceso3 = false;
bool acceso4 = false;
int count = 0;
int intparse = -1;
if (FL.ValidaAcceso(int.Parse(Request.QueryString["IDSubForma"].ToString()), 3, ((clsUsuario)Session["clsUsuario"]).IDUsuario))
{
acceso1 = true;
count = count + 1;
}
if (FL.ValidaAcceso(int.Parse(Request.QueryString["IDSubForma"].ToString()), 2, ((clsUsuario)Session["clsUsuario"]).IDUsuario))
{
acceso2 = true;
count = count + 1;
}
if (FL.ValidaAcceso(int.Parse(Request.QueryString["IDSubForma"].ToString()), 1, ((clsUsuario)Session["clsUsuario"]).IDUsuario))
{
acceso3 = true;
count = count + 1;
}
if (FL.ValidaAcceso(int.Parse(Request.QueryString["IDSubForma"].ToString()), 4, ((clsUsuario)Session["clsUsuario"]).IDUsuario))
{
acceso4 = true;
count = count + 1;
}
if (count > 1)
{
intparse = lblAcceso.Text.Equals("") ? 0 : (Int32.TryParse(lblAcceso.Text, out intparse) ? intparse : 0);
if (intparse <= 0)
{
//IDENTIFICAR QUE BOTONES MOSTRAR
if (acceso1 == false)
{
wcFirmas.Visible = false;
btn1.Visible = false;
}
if (acceso2 == false)
{
wcFirmas.Visible = false;
btn2.Visible = false;
}
if (acceso3 == false)
{
wcFirmas.Visible = false;
btn3.Visible = false;
}
if (acceso4 == false)
{
wcFirmas.Visible = false;
btn4.Visible = false;
}
divMultipleAcceso.Visible = true;
divForma.Visible = false;
}
}
else if (acceso1 == true)
{
lblAcceso.Text = "3";
divForma.Visible = true;
cargarForma(txtNoLote);
}
else if (acceso2 == true)
{
lblAcceso.Text = "2";
divForma.Visible = true;
cargarForma(txtNoLote);
}
else if (acceso3 == true)
{
lblAcceso.Text = "1";
divForma.Visible = true;
cargarForma(txtNoLote);
}
else if (acceso4 == true)
{
lblAcceso.Text = "4";
divForma.Visible = true;
cargarForma(txtNoLote);
}
else
{
divForma.Visible = false;
Master.MostrarMsn("El usuario no cuenta con privilegios de acceso.", 0);
return;
}
}
catch (Exception ex) { Master.MostrarMsn(ex.Message, 0); }
}
I save the rol number into a label to compare it in every control of the form to see if I need to display it or not. Then I do something like:
if(lblAcceso.Text.Equals("2"))
The problem is, if I add an extra rol to this form, (for example, rol 5) then I have to modify the code. The goal is to modify the code as little as possible.
Thanks everyone that have comment so far.
ASP.net role management:
https://msdn.microsoft.com/en-us/library/5k850zwb.aspx
if (!Roles.IsUserInRole(User.Identity.Name, "ROLENAME"))
{
UsersListBox.Visible = false;
return;
}
https://msdn.microsoft.com/en-us/library/4z6b5d42(v=vs.110).aspx
Assuming you are configured to use the built in .net role provider
you can do
if (this.User.IsInRole("RoleName"))
{YourControl.Visible = true }
or
YourControl.Visible = this.User.IsInRole("RoleName")

Radiobuttons, how to replace all those if statements

Several places in my program, the RadioButton matching the selected item has to be checked, and I have a lot of if statements like so:
DataRowView TempRow = (DataRowView)ScheduleDataGrid.SelectedItem;
if (Convert.ToString(TempRow["Bio"]) == "Bio1")
{
BioRB1.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio2")
{
BioRB2.IsChecked = true;
}
if (Convert.ToString(TempRow["Bio"]) == "Bio3")
and so on... I want to replace all this with something short and smart.
I tried using the number of the bio to relate to the button like so:
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
BioRB[i].IsChecked = true;
but doing a BioRB[i] doesn't work, it ignores the [i] and says BioRB does not exist. Any other suggestions?
BioRB[i] is not doing anything like what you think it's doing. All variable references (controls included) have to be well-defined at compile time - you can't refer to a control's name by building a string that matches the name.**
Try creating a list of your radio buttons. Then you can index into the list:
List<RadioButton> radioButtons = new List<RadioButton>()
{
BioRB1,
BioRB2
};
string bioselected = Convert.ToString(TempRow["Bio"]);
int i = Convert.ToInt16(bioselected.Substring(bioselected.Length - 1, 1));
radioButtons[i].IsChecked = true;
** Technically you can do this via reflection, but it's far more complex than what you've tried.
Maybe this will look better:
string caseSwitch = Convert.ToString(TempRow["Bio"]);
switch (caseSwitch)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...is optional");
break;
}
Also, try doing what Alybaba726 said and use CellContentClick or something like this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if(e.ColumnIndex == dgv.Columns["Bio"].Index)
{
string bioSelected = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
switch (bioSelected)
{
case "Bio1":
BioRB1.IsChecked = true;
break;
case "Bio2":
BioRB2.IsChecked = true;
break;
case "Bio3":
BioRB3.IsChecked = true;
break;
default:
Console.WriteLine("Default case...this is optional");
break;
}
}
}

DatagridView Checkbox Column is always null

I have a strange issue.
Basically I have a datagridview and a button. When I click this button it checks all rows for column 1s value - the checkbox column. It then sets it to true / false depending on what it currently is.
Thats all fine.
But then, I have another button to do something with these rows that are ticked. I click it and it only ever identifies the first row as being ticked. The rest are apparently null now..?
So, how can I programmtically set the value of a checkbox column in a datagrid view and then read it again cause Im apparently way off the mark based on my results.
This sets the tick boxs and I can see them, untick them manually etc.
foreach (DataGridViewRow row in dgv.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
}
Then the next button to check values is just finding nulls
foreach (DataGridViewRow row in rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = true;
break;
case "False":
ch1.Value = false;
break;
}
var val = row.Cells["EbayListingID"].Value.ToString();
if (ch1.Value.ToString() == "true") continue;
var listing = dsEntities.EbayListings.First(x => x.EbayListingID.ToString() == val);
SubmitListingForReview(listing, false);
}
First,
if (ch1.Value.ToString() == "true") continue;
Why is string constant is "true", but not "True"?
Second, in the next button click handler, what is it "rows"?
foreach (DataGridViewRow row in rows)
I try this code and it works fine :
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = false;
break;
case "False":
ch1.Value = true;
break;
}
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var ch1 = new DataGridViewCheckBoxCell();
ch1 = (DataGridViewCheckBoxCell)row.Cells[0];
if (ch1.Value == null)
ch1.Value = false;
switch (ch1.Value.ToString())
{
case "True":
ch1.Value = true;
break;
case "False":
ch1.Value = false;
break;
}
var val = row.Cells[1].Value;
if (ch1.Value.ToString() == "True") continue;
MessageBox.Show("1");
}
}

DataGridview search: show only searchresult and hide other rows?

What should I add to my code to only show the results of my search?
Right now when I search the searchresult becomes selected (highlighted) and the others remain the same.
Been trying to hide the other rows but without any success (and only show the searchresult, alone). Any suggestions?
Im using a datagridview.
My code:
private void button3_Click_1(object sender, EventArgs e)
{
string search = textBox1.Text;
for (int i = 0; i < dgTest.Rows.Count; i++)
{
if (dgTest.Rows[i].Cells[0].Value.ToString() == search)
{
dgTest.Rows[i].Selected = true;
break;
}
else
{
dgTest.Rows[i].Selected = false;
}
}
}
If your DataGridView is not bound to a data source, then setting the row's Visible property to false will hide it:
for (int i = 0; i < dgTest.Rows.Count; i++)
{
var row = dgTest.Rows[i];
if (row.Cells[0].Value.ToString() == search)
{
row.Selected = true;
row.Visible = true;
}
else
{
row.Selected = false;
row.Visible = false;
}
}
(I removed the 'break' command, as even after you have found the matching row, you would want to continue and hide the other rows.)
If you're using DataBinding, though, it's not so easy, as shown in this page.
you can try this:
for (int i = 0; i < dgTest.Rows.Count; i++)
{
if (dgTest.Rows[i].Cells[0].Value.ToString() == "search")
{
dgTest.Rows[i].Selected = true;
dgTest.Rows[i].Visible = true;
}
else
{
dgTest.Rows[i].Visible = false;
dgTest.Rows[i].Selected = false;
}
}

Categories

Resources