How to clear ComboBox text when DropdownStyle is DropDown - winforms

I have a ComboBox whose DropdownStyle is DropDown. So, I can select from the list or can type own data.
When I click on the clear button, text typed in the ComboxBox should be removed.
I have already tried "object.text = string.Empty;" but not working.
public ComboBox cmb_Identifier(int x, int y)
{
cntrlObjList.comboBoxIdentifier.Items.Clear();
cntrlObjList.comboBoxIdentifier.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDown;
cntrlObjList.comboBoxIdentifier.FormattingEnabled = true;
cntrlObjList.comboBoxIdentifier.Location = new System.Drawing.Point(x, y);
cntrlObjList.comboBoxIdentifier.Name = "cmbIdentifier";
cntrlObjList.comboBoxIdentifier.Size = new System.Drawing.Size(151, 21);
cntrlObjList.comboBoxIdentifier.TabIndex = 6;
cntrlObjList.comboBoxIdentifier.Visible = true;
cntrlObjList.comboBoxIdentifier.Items.Add("Identifier 1");
cntrlObjList.comboBoxIdentifier.Items.Add("Identifier 2");
return cntrlObjList.comboBoxIdentifier;
}
public void btnClear_Click(object sender, EventArgs e)
{
cntrlObjListMain.comboBoxIdentifier.SelectedText = string.Empty(); //not working
}

I found the solution and it is working in my case.
cntrlObjList.comboBoxIdentifier.Text = null;

The following should work for you
cntrlObjList.comboBoxIdentifier.Text = String.Empty;
or
cntrlObjList.comboBoxIdentifier.Text = "";

Related

How do I call a control that was created dynamically in c#

First, a great thank you to those who asked/responded to questions. You were able to get me this far.
I wanted to help a young Belgian entrepreneur by taking on a challenge, build a Media managing software to display various media types (Images, Videos, links, text) on huge LED screens.
I have limited coding experience as I work in EDI.
My issue is that I create playlists dynamically based on the number of playlists in the DB (see screenshot), but I cannot trigger the playing of the right playlist when pressing the play button.
Warning, my code is noob code.
PlayList ScreenShot
Label playListLbl = new Label();
GroupBox playListGrp = new GroupBox();
public GroupBox addplayListGrp(int i, int start, int end)
{
GroupBox playListGrp = new GroupBox();
playListGrp.Name = "playListGrp"+ Convert.ToString(1 + i);
playListGrp.Text = "Play list " + Convert.ToString(1 + i);
playListGrp.Font = new Font("Century Gothic", 12F,
FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
playListGrp.Width = 425;
playListGrp.Height = 525;
playListGrp.Margin = new Padding(1);
playListGrp.Location = new Point(start, end);
return playListGrp;
}
Button addPlayBtn(int i)
{
Button PlayBtn = new Button();
PlayBtn.Font = new Font("Century Gothic", 9.75F,
System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
PlayBtn.ForeColor = Color.Black;
PlayBtn.Location = new Point(10, 467);
PlayBtn.Name = "playBtn" + Convert.ToString(1 + i);
PlayBtn.Size = new Size(100, 30);
PlayBtn.TabIndex = 6;
PlayBtn.Text = "Play";
PlayBtn.UseVisualStyleBackColor = true;
PlayBtn.Click += new EventHandler(playBtn1_Click);
return PlayBtn;
}
public BMS_main()
{
int startPos = 5;
int endPos = 5;
for (int i = 1; i <= playlistCountInc; i++)
{
playListGrp = addplayListGrp(i, startPos, endPos);
playListLbl = addLabel(i);
Label playListLblTime = addLabelTime(i);
Button PlayBtn = addPlayBtn(i);
}
playListGrp.Controls.Add(playListLbl);
playListGrp.Controls.Add(playListLblTime);
playListGrp.Controls.Add(playlistView);
playListGrp.Controls.Add(PlayBtn);
}
private void playBtn1_Click(object sender, EventArgs e)
{
if (ScreenStatus)
{
Playing = true;
DisplayTimer.Stop();
DisplayTimer.Enabled = false;
InitialScreenTimer.Stop();
InitialScreenTimer.Enabled = false;
PlayListTimer.Enabled = true;
PlayListTimer.Start();
}
else
{
message = "Veuillez alimenter les panneaux";
result = MessageBox.Show(message, caption, buttons);
}
public void PlayListTimer_Tick(object sender, EventArgs e)
{
Label lblAcessorio4 =
(Label)playListLbl.Controls.Find("playLbl4",
true).FirstOrDefault();
if (lblAcessorio4 != null)
{
lblAcessorio4.Text = "Test lblAcessorio4";
}
else
{
message = "Label is null";
result = MessageBox.Show(message, caption, buttons);
}
Set the Tag property of your button with something which will help you decide later on which song to play:
playListGrp = addplayListGrp(i, startPos, endPos);
playListLbl = addLabel(i);
Label playListLblTime = addLabelTime(i);
Button PlayBtn = addPlayBtn(i);
// You can do this
PlayBtn.Tag = playListGrp; // or anything else
Then in the button click handler, get the value of the Tag and make a decision based on that. Just keep in mind that whatever you set the Tag to, you will need to cast it back to that type. For example, in the above I set it GroupBox so I will cast it to a GroupBox:
private void playBtn1_Click(object sender, EventArgs e)
{
GroupBox gb = ((Button)(sender)).Tag as GroupBox;
// Now make the decision
if(gb.Name == "whatever you need to put here"){ // do whatever }
}
I would put the lisbox and then get the selected item and play that.

datagridview control continues update, gui flickers when scrolling window

Problem:
I have a Winform application with a form en on this form i have a databound DataGridView.
The datagridview is updated from the backend by updating the bind object continuesly using a timer to get the data every 10 seconds. In order to update the gui with this new data i call a RefreshDatabindings. (if i do not do this, the gui is nog updated, i am binding to a BindingList and the object implement the INotifyPropertyChanged)
When the form is big enough to show the whole datagridview at once everything is working wel. But when the form is not big enough to show the hole datagridview a scrollbar appears.
When i scroll to the right to see the rest of the datagridview i see the gui flickering (only the part that wasn't visible before scrolling). When i strech the form to make de gridview fitting again, everything is working wel (no flashing and flickering). the flickering only happens when i have to scroll.
I am lost, can please somebody help me :)?
I allready tryed the DoubleBuffered = true.
Thanks in advance!
BindingList<InstanceTableViewModel> viewModelList;
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
functionParamList = new List<FunctionParameter>();
functionParamList.Add(new FunctionParameter { DeviceValue = 100, InstanceId = "1", Name = "A" });
functionParamList.Add(new FunctionParameter { DeviceValue = 200, InstanceId = "2", Name = "B" });
functionParamList.Add(new FunctionParameter { DeviceValue = 300, InstanceId = "3", Name = "C" });
viewModelList = CreateInstanceTableViewModelList();
dataGridView1.DataSource = viewModelList;
//Create timer
updateDataTimer = new System.Timers.Timer();
updateDataTimer.Interval = 500;
updateDataTimer.Elapsed += updateDataTimer_Elapsed;
updateDataTimer.Start();
}
private void updateDataTimer_Elapsed(object sender, ElapsedEventArgs e)
{
ThreadPool.QueueUserWorkItem(ReadDataThreadPoolMethod);
}
private void ReadDataThreadPoolMethod(object state)
{
Random random = new Random();
int randomNumber = random.Next(0, 100);
foreach (FunctionParameter param in functionParamList)
{
param.DeviceValue = Convert.ToInt64(randomNumber);
}
}
void functionParameter_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var functionParameter = sender as FunctionParameter;
var propertyName = e.PropertyName;
var propertyValue = functionParameter.DeviceValue;
var parameterName = functionParameter.Name;
UpdateViewModel(functionParameter.InstanceId, propertyName, propertyValue, parameterName);
}
private void UpdateViewModel(string instanceId, string propertyName, long propertyValue, string parameterName)
{
var instanceViewModel = viewModelList.Single(x => x.InstanceId == instanceId && x.NameLabel == parameterName);
if (instanceViewModel != null)
{
instanceViewModel.ValueHex = Convert.ToUInt16(propertyValue);
}
ResetBindingsSource();
}
delegate void UpdateBindingsInvoker();
public void ResetBindingsSource()
{
if (!this.IsDisposed)
{
if (this.InvokeRequired)
{
this.Invoke(new UpdateBindingsInvoker(UpdateDataGrid));
}
else
{
UpdateDataGrid();
}
}
}
private void UpdateDataGrid()
{
dataGridView1.Refresh();
}
So here my solution:
You only uses the Forms DoubleBuffering, but the following code is an extension method to the DataGridview and successfully works (at my tests ;)
public static void DoubleBuffered(this DataGridView dgv, bool setting)
{
Type dgvType = dgv.GetType();
PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
BindingFlags.Instance | BindingFlags.NonPublic);
pi.SetValue(dgv, setting, null);
}
I found this code right here at Codeprojct.
You can use it in this way:
YourDataGridView.DoubleBuffered(true);
I hope i could help you ^^

unable to set Row.Readonly=false in Datagridview in winforms

I have a datagridview with its ReadOnly set true to prevent people editing.
then I have a button on each row. when I click on a specific button, I wrote:
private void DGGrade_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > 0 && e.ColumnIndex == DGGrade.Columns["Edit"].Index)
{
DGGrade.Rows[DGGrade.CurrentCell.RowIndex].ReadOnly = false;
DGGrade.Rows[DGGrade.CurrentCell.RowIndex].DefaultCellStyle.BackColor = Color.White;
}
But it is not working. please help
I do not know the reason why it is not working but as far as i can tell from my test runs it has to deal how the data is bound. If you use dataGridView1.DataSource = GetDataSource(); then it did not work in my tests. I have read once about some of the drawbacks of automated binding but i could not find it. Here is the code that works. A row is only in EditMode after the User has clicked the button Edit in the corresponding row. I will be back later - let me know if you need more pointers.
public partial class Form1 : Form
{
int rowIndexOfEditableRow = -1;
public Form1() {
InitializeComponent();
CreateDataGridView(dataGridView1);
SetExistingDataGridViewRowsReadOnly();
this.dataGridView1.Columns.Add(GetBtnColumn());
}
private void SetExistingDataGridViewRowsReadOnly() {
DataGridViewRowCollection rows = this.dataGridView1.Rows;
foreach (DataGridViewRow row in rows) {
row.ReadOnly = true;
}
}
It seems that the grid must be filled manually - at least this way the change of ReadOnly works
public void CreateDataGridView(DataGridView dgv)
{
dgv.ColumnCount = 3;
dgv.Columns[0].Name = "Id";
dgv.Columns[1].Name = "Lastname";
dgv.Columns[2].Name = "City";
dgv.BackgroundColor = Color.Gray;
AddRowsToDataGridView(dgv);
}
private void AddRowsToDataGridView(DataGridView dgv)
{
string[] row1 = new string[]{"1", "Muller", "Seattle"};
string[] row2 = new string[]{"2", "Arkan", "Austin"};
string[] row3 = new string[]{"3", "Cooper", "New York"};
object[] rows = new object[] { row1, row2, row3 };
foreach (string[] rowArray in rows)
{
dgv.Rows.Add(rowArray);
}
}
Helper method to create a column with a button
public DataGridViewButtonColumn GetBtnColumn()
{
DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn();
btnColumn.HeaderText = "Edit";
btnColumn.Text = "Edit";
btnColumn.UseColumnTextForButtonValue = true;
return btnColumn;
}
Event handler checks if the user has clicked the edit button. In this case the current row will be set to ReadOnly = false. This allows that the user to edit the row. To emphasize it i changed the background color of the row.
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int colIndex = e.ColumnIndex;
int rowIndex = e.RowIndex;
Type cellType = dataGridView1.Columns[colIndex].CellType;
if (cellType == typeof(DataGridViewButtonCell))
{
dataGridView1.Rows[rowIndex].ReadOnly = false;
dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = Color.GreenYellow;
this.rowIndexOfEditableRow = rowIndex;
label1.Text = rowIndexOfEditableRow.ToString() + " " + colIndex.ToString();
}
}
If the Row-leave-Event is fired the style is reset and the global parameter which row is editable is set to the initial value
private void DataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
dataGridView1.Rows[rowIndex].ReadOnly = true;
dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = Color.White;
this.rowIndexOfEditableRow = -1;
}
}
The above code contains all (except the designer files) that you need to create this demo:

RepositoryItemCheckEdit doesn't stay checked

I try to add a RepositoryItemCheckEdit to my GridView using devexpress and Winforms. However, I can get only one checkbox be checked. If I check another one, the checkbox I checked before becomes unchecked. I followed everything I can find on the net, but couldn't make this work. What am I missing?
The code part I insert the column:
gcIsEmirleri.DataSource = (from i in isemirleri
select new
{
ID = i.isEmriId,
// other attributes
}).ToList();
GridColumn column = gvIsEmirleri.Columns["Sec"];
if (column == null)
{
gvIsEmirleri.BeginUpdate();
DataColumn col = new DataColumn("Sec", typeof(bool));
column = gvIsEmirleri.Columns.AddVisible("Sec");
col.VisibleIndex = 0;
col.Caption = "Sec";
col.Name = "Sec";
col.OptionsColumn.AllowEdit = true;
gvIsEmirleri.EndUpdate();
gvIsEmirleri.Columns["Sec"].UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
RepositoryItemCheckEdit chk = new RepositoryItemCheckEdit();
chk.ValueChecked = true;
chk.ValueUnchecked = false;
gvIsEmirleri.Columns["Sec"].ColumnEdit = chk;
chk.QueryCheckStateByValue += chk_QueryCheckStateByValue;
}
The code part I make the checkbox two-stated instead of three:
private void chk_QueryCheckStateByValue(object sender, DevExpress.XtraEditors.Controls.QueryCheckStateByValueEventArgs e)
{
if (e.Value == null)
{
e.CheckState = CheckState.Unchecked;
e.Handled = true;
}
}
EDIT: I created a List<bool> chkList; and do the following operations:
This function is added to checkedits' CheckStateChanged:
private void chk_CheckStateChanged(object sender, EventArgs e)
{
CheckEdit chk = sender as CheckEdit;
if (chk.Checked)
chkList[gvIsEmirleri.FocusedRowHandle] = true;
else
chkList[gvIsEmirleri.FocusedRowHandle] = false;
FillBindingSource();
}
In FillBindingSource I added the lines:
for (int i = 0; i < chkList.Count; i++)
{
if (chkList[i])
gvIsEmirleri.SetRowCellValue(i, "Sec", true);
}
I debug these lines, I see that List has correct bool values and gvIsEmirleri.SetRowCellValue(i, "Sec", true); is operated when it has to. However, it still doesn't work.
My guess is : You are using an unbound Column, and you are not saving the checked / unckecked info, so, after the selected row is left, the checkBox get it's initial value (unckecked).
For this, I suggest you handle the CustomUnboundColumnData event of your view. Here is a simple :
readonly Dictionary<object, bool> checkedMap = new Dictionary<object, bool>();
private void viewScales_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
{
// Check what column
if (e.Column != gvIsEmirleri.Columns["Sec"])
return;
if (e.IsGetData)
{
// check if the row has been checked and set it's value using e.Value
bool checked;
if (checkedMap.TryGetValue(e.Row, out checked))
e.Value = checked;
}
if (e.IsSetData)
{
var checked = Convert.ToBoolean(e.Value);
// Check if the key already exist
if (checkedMap.ContainsKey(e.Row))
scaleMap.Remove(e.Row);
checkedMap.Add(e.Row, checked);
}
}
Note : This is the way I resolved a similar problem, but I did not test the code I just wrote.

Finding controls in Windows Forms C# .NET?

Using Windows Forms, two link labels are created dynamically. When the user clicks on anyone of links labels, one dynamic form is created. In that form I created one data grid, a text box and a button placed dynamically (in that dynamic form). Now I want to access the dynamic data grid in the dynamic button click event. How can I do that?
private void Users_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("Usp_Get_Employees", con);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string somecode = i.ToString() + ds.Tables[0].Rows[i]["eid"].ToString();
LinkLabel lbluser = new LinkLabel();
lbluser.Name = ds.Tables[0].Rows[i]["eid"].ToString();
lbluser.Text = ds.Tables[0].Rows[i]["ename"].ToString();
lbluser.Location = new System.Drawing.Point(40, i * 40);
lbluser.Size = new System.Drawing.Size(50, 30);
Controls.Add(lbluser);
lbluser.Click += new EventHandler(lbluser_Click);
}
}
}
void lbluser_Click(object sender, EventArgs e)
{
LinkLabel lnkClis = (LinkLabel)sender;
Form frm = new Form();
frm.Name = lnkClis.Name;
frm.Text = lnkClis.Text;
frm.Show();
DataGrid dtgrd = new DataGrid();
dtgrd.Location = new System.Drawing.Point(10, 1 * 40);
dtgrd.Name = lnkClis.Name;
names = lnkClis.Name;
TextBox tx = new TextBox();
tx.Location = new System.Drawing.Point(10, 5 * 40);
tx.Size = new Size(80, 30);
tx.Multiline = true;
tx.LostFocus += new EventHandler(tx_LostFocus);
Button btn = new Button();
btn.Location = new System.Drawing.Point(10, 7 * 40);
btn.Size = new System.Drawing.Size(50, 30);
btn.Name = lnkClis.Name;
btn.Click += new EventHandler(btn_Click);
frm.Controls.Add(dtgrd);
frm.Controls.Add(tx);
frm.Controls.Add(btn);
}
// Now I am trying to access the data grid in the btn_click event
void btn_Click(object sender, EventArgs e)
{
Button btsave = (Button)sender;
string eid = btsave.Name;
object grd = btsave.Parent.Controls.Find("dtgrd", true).FirstOrDefault();
((DataGrid)grd).DataSource = ds.Tables[0];
}
Now I am getting an error object set of instances of an object at:
((DataGrid)grd).DataSource = ds.Tables[0];
The exception message you have written:
Now I am getting an error object set of instances of an object at
makes no sense, but it looks like
Object reference not set to an instance of an object
If this is the case, I think the error lays in Find method call. According to documentation:
Searches for controls by their Name property and builds an array of all the controls that match.
In your button click handler you assume that grid is called dtgrd, but while you create a grid you name it like this:
dtgrd.Name = lnkClis.Name;
it will suffice if you change this line to:
dtgrd.Name = "dtgrd";
Having said that, you should consider using an anonymous method for the button click handler. It will eliminate need for calling the Find method in the first place.
void lbluser_Click(object sender, EventArgs e)
{
//...
DataGrid dtgrd = new DataGrid();
//...
Button btn = new Button();
//...
btn.Click += (sender,args)=> dtgrd.DataSource = ds.Tables[0];
Try the following code
public Form1()
{
Form f1 = new Form();
f1.Text = "New Form";
TextBox t1 = new TextBox();
t1.Top = 0;
t1.Name = "t1";
t1.Visible = true;
f1.Controls.Add(t1);
Button b1 = new Button();
b1.Top = 30;
b1.Name = "b1";
b1.Text = "Click";
b1.Click += b1_Click;
f1.Controls.Add(b1);
f1.Show();
}
public void b1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
object txt = btn.Parent.Controls.Find("t1", false).First();
((TextBox)txt).Text = "Hi, you have clicked me.";
}
I modified Nitesh's code a bit. Just capture the textbox in the click handler using a lambda:
public Form1()
{
Form f1 = new Form();
f1.Text = "New Form";
TextBox t1 = new TextBox();
t1.Top = 0;
t1.Name = "t1";
t1.Visible = true;
f1.Controls.Add(t1);
Button b1 = new Button();
b1.Top = 30;
b1.Name = "b1";
b1.Text = "Click";
b1.Click += (sender, args) => MessageBox.Show("The text is: " + t1.Text);
f1.Controls.Add(b1);
f1.Show();
}
The error you are getting is from the statement (as the grd object is null):
((DataGrid)grd).DataSource = ds.Tables[0];
Since you are trying to catch hold of a dynamic control, it's good have a proper null checks, type checks, and error handling. Something like this:
if(grd != null && grd is DataGrid)
((DataGrid)grd).DataSource = ds.Tables[0];

Resources