DataGridViewLinkCell event crash desktop app - c#

I tried to make simple CRUD desktop app with Visual Studio C# following some tutorials.
I have connected a small SQL Server and everything ok until I've implemented 2 link buttons to edit and erase. Now every time I click on any other cell that comes with the query, app crash.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace URL_API_v2
{
public partial class MLA_URL : Form
{
private CN_MLA _CN_MLA;
public MLA_URL()
{
InitializeComponent();
_CN_MLA = new CN_MLA();
}
#region EVENTOS
private void btnAgregar_Click(object sender, EventArgs e)
{
OpenMLAadd();
}
#endregion
#region Metodos Privados
private void OpenMLAadd()
{
AgregarMLA agregarMLA = new AgregarMLA();
agregarMLA.ShowDialog(this);
}
#endregion
private void MLA_URL_Load(object sender, EventArgs e)
{
Populate();
}
public void Populate(string Buscar = null)
{
List<tablaMLA> consulta = _CN_MLA.GetMLAs(Buscar);
MLA.DataSource = consulta;
}
private void MLA_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewLinkCell cell = (DataGridViewLinkCell)MLA.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell.Value.ToString() == "EDITAR")
{
AgregarMLA agregarMLA = new AgregarMLA();
agregarMLA.LoadContact(new tablaMLA
{
URL_ID = int.Parse(MLA.Rows[e.RowIndex].Cells[0].Value.ToString()),
URL_QUERY = (MLA.Rows[e.RowIndex].Cells[1]).Value.ToString()
});
agregarMLA.ShowDialog(this);
}
else if (cell.Value.ToString() == "BORRAR")
{
BorrarMLA(int.Parse(MLA.Rows[e.RowIndex].Cells[0].Value.ToString()));
Populate();
}
}
private void BorrarMLA (int URL_ID)
{
_CN_MLA.BorrarMLA(URL_ID);
}
private void btnBuscar_Click(object sender, EventArgs e)
{
Populate(txtSearch.Text);
txtSearch.Text= string.Empty;
}
}
}
Can anyone have a look? Basically this Main outputs a DataGrid with a basic "select * from table1" with 2 additional (not linked columns) with a the text "edit" and "erase" so you can click on them and do that. BUT, wherever you click on another random cell, error comes up with something like:
Cannot convert DataGridViewLinkCell to DataGridViewTextBox
and if you debug first line in the "MLA_CellContentClick" is highlighted.

Assuming your error was the other way around, which I suspect it must be, then first test whether the cell is of the type you are trying to cast it to, and if not just return without further processing.
private void MLA_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if !(MLA.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell) return;
var cell = MLA.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewLinkCell;
// ...
}

Related

How to Rotate Label 90 Degrees in C#

I have a desktop application that projects names to the screen based on the numbers received from the card reader. However, the screen is sideways, so I want the names to appear on the screen rotated 90 degrees. How can I do it?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Reader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "0013864285")
{
label1.Text = "Roy Randle";
textBox1.Clear();
}
if (textBox1.Text == "0016657328")
{
label1.Text = "Jake Garrett";
textBox1.Clear();
}
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += this.textBox1_TextChanged;
}
I made several attempts but no success.
One solution is to display the text characters vertically:
public string RotateText(string input)
{
var charArray=input.ToCharArray();
return string.Join("\n", charArray);
}
// use this function
label1.Text = RotateText("Roy Randle");

Open a new form by reading comboBox value

I'm not very versed in coding, let's say this is some kind of project I started without knowing anything about coding.
I have a Button which should read the selection in the comboBox and then open a specific form.
I've tried using following the switch (comboBox1.SelectedText)
While that didn't quite work, I tried another approach:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace The_Liberion_Magnicite
{
public partial class Form1 : The_Liberion_Magnicite.Character
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedText.ToString();
{ if (comboBox1.SelectedText.ToString() == "Shiroichi Kazami (PTS)")
{
this.Hide();
Shiro1 CShiro1 = new Shiro1();
CShiro1.Show();
}
else if (comboBox1.SelectedText.ToString() == "Shiroichi Kazami (ATS)")
{
this.Hide();
Shiro2 CShiro2 = new Shiro2();
CShiro2.Show();
}
else if (comboBox1.SelectedText.ToString() == "Akari Hondo")
{
this.Hide();
AkariHondo CAkari = new AkariHondo();
CAkari.Show();
}
else if (comboBox1.SelectedText.ToString() == "Aboa Sekihara")
{
this.Hide();
AobaSeki CAoba = new AobaSeki();
CAoba.Show();
}
}
}
}
}
I'm in some dire need for help ;)

C# Gridview- Focus and change specific value for database

I have built a gridview in a C# form that allows me to edit in a database in a single form. However, I want it to operate in a different way:
When I double click a row, it opens ONLY the specific row, with the corresponding columns in a single form.
As soon as it opens, I edit the row. It saves in the database.
What I want to try to do is:
SELECT ColumnName1, ColumnName2
FROM TableName
WHERE ColumnName1 = #ParameterName
Where the parameter name is the ID in which i double click i another form. I am putting my work so far:
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestInventory
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'prismaWinPosDataSet.Inventory' table. You can move, or remove it, as needed.
this.inventoryTableAdapter.Fill(this.prismaWinPosDataSet.Inventory);
}
private void simpleButton1_Click(object sender, EventArgs e)
{
// inventoryBindingSource.Update(prismaWinPosDataSet,"Inventory");
gridView1.PostEditor(); //save the cell value to a data source
gridView1.UpdateCurrentRow(); //update the row and raise the RowUpdated event
// dbContext
inventoryTableAdapter.Update(this.prismaWinPosDataSet.Inventory);
}
// Cell validation rules
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// context.SubmitChanges();
}
private void simpleButton3_Click(object sender, EventArgs e)
{
inventoryBindingSource.AddNew();
}
private void simpleButton4_Click(object sender, EventArgs e)
{
if (XtraMessageBox.Show("Delete?", "Message",MessageBoxButtons.YesNo, MessageBoxIcon.Question)==DialogResult.Yes);
inventoryBindingSource.RemoveCurrent();
}
private void gridView1_DoubleClick(object sender, EventArgs e)
{
// int invID = gridView1.GetRow;
Form2 frm = new Form2(2);
frm.ShowDialog();
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
}
}
}
Single form is working normally, updating in the database.
Message box "ok" is because I haven't accomplished to connect it to the query in the second form.

Combobox, clickable links within a listbox in winforms

I'm trying to design a add-remove containers in C# winforms. I'm trying to achieve it by using listbox. Now, my listbox1 contains combobox, and other items. I've 2 questions in this regard:
Which control should I use in order to define the non-combo box items? In other forms, selecting these controls would open an excel sheet. It would be a similar operation in this case, by filtering the data based on the values selected in combo box.
How do I create this listbox1 and listbox2? Also, the code I've written so far for adding and removing items from one listbox to another, is correct?
Here's the overall code written so far.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class DataFilter : Form
{
public DataFilter()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
this.Controls.Clear();
this.InitializeComponent();
}
private void indexerbtn_Click(object sender, EventArgs e)
{
Indexer ins = new Indexer();
ins.MdiParent = this.MdiParent;
this.Hide();
ins.ShowDialog();
}
private void MoveListBoxItems(ListBox source, ListBox destination)
{
ListBox.SelectedObjectCollection sourceItems = source.SelectedItems;
foreach (var item in sourceItems)
{
destination.Items.Add(item);
}
while (source.SelectedItems.Count > 0)
{
source.Items.Remove(source.SelectedItems[0]);
}
}
private void button1_Click(object sender, EventArgs e)
{
MoveListBoxItems(listBox1, listBox2);
}
private void button2_Click(object sender, EventArgs e)
{
MoveListBoxItems(listBox2, listBox1);
}
}
}
...........................................................................................
Please let me know your e-mail address. I can send across the screenshot of the design which could explain the objective better.

Copy/Paste in Windows Forms with custom controls

I am writing a small application in C# using Windows Forms. I want to let my users copy and paste data around the application and there are some custom controls, for example one is a colour picker.
Some of the default controls (well at least the TextBox) have a copy and paste functionality already. I want to have the same thing with my colour picker, and also want an 'Edit' menu at the top to copy and paste.
At the moment, I can't see how to do this in a nice way, my current tack is to catch the Ctrl + C and Ctrl + V commands and the menu clicks and go through a function which uses some Win32 calls to find the focused control and then copy or paste data from or to the control (with a massive if statement depending on the type of the focused control).
The alternative seems to be to write key handling into every custom control, but with this method I'm not sure how to incorporate the Edit menu functions.
How do I do this in an elegant or more 'standard' way?
The simplest way is to activate KeyPreview in the form and then follow the logic in KeyDown event.
But an other approach can be useful:
If you have in your win application a menu (by e.g. &Edit => Copy (Paste)).
Enable for that menus the keyboard shortcuts
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new
System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem});
this.editToolStripMenuItem.Text = "Edit";
//
// copyToolStripMenuItem
//
**this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)
((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));**
this.copyToolStripMenuItem.Text = "&Copy";
//
// pasteToolStripMenuItem
//
**this.pasteToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)
((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.V)));**
this.pasteToolStripMenuItem.Text = "&Paste";
So you have your shortcuts to Copy paste. Now manage just your menu clicks
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
Image myData = this.ActiveControl.BackgroundImage;
Clipboard.SetImage(myData);
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
Image myData = Clipboard.GetImage();
this.ActiveControl.BackgroundImage = myData;
}
Surely, you can make invisible your menu, if you want do not show it to the user.
===============================================================================
UPDATE
code for multiple controls:
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
ICopyPasteable control = sender as ICopyPasteable;
if (control != null)
{
control.CopyToClipboard();
}
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
ICopyPasteable control = sender as ICopyPasteable;
if (control != null)
{
control.PasteFromClipboard();
}
}
}
public interface ICopyPasteable
{
void CopyToClipboard();
void PasteFromClipboard();
}
public class MyTextBox : TextBox, ICopyPasteable
{
#region ICopyPasteable Membres
public void CopyToClipboard()
{
Clipboard.SetText(this.Text);
}
public void PasteFromClipboard()
{
if (Clipboard.ContainsText())
{
this.Text = Clipboard.GetText();
}
}
#endregion
}
To find the focussed control: ContainerControl.ActiveControl. Then depending on the type of control, you can set a value (with the clipboard value).
The KeyUp event solved my problem! Events KeyDown and KeyPress didn't catch Ctrl + C for copy!
From Stack Overflow question Catching Ctrl + C in a textbox:
private void txtConsole_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C | Keys.Control))
{
_consolePort.Write(new byte[] { 3 }, 0, 1);
e.Handled = true;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace notep
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void b1_Click(object sender, RoutedEventArgs e)//copy
{
Clipboard.SetText(richTextBox1.Selection.Text);
richTextBox1.Selection.Text = string.Empty;
}
private void b2_Click(object sender, RoutedEventArgs e)//cut
{
Clipboard.SetText(richTextBox1.Selection.Text);
}
private void b3_Click(object sender, RoutedEventArgs e)
{
richTextBox1.Selection.Text =richTextBox1.Selection.Text + Clipboard.GetText();//paste
}
}
}

Categories