Refresh listbox after adding - c#

I have a listbox in C# and want it to refresh after I added a new item(which gets opened with a new form dialog)
Here is my code which doesn't work.
private void showAllItems()
{
itemList = Db.getAllItems();
lb_itemList.DataSource = itemList;
}
private void showItemPreview(object sender, EventArgs e)
{
string curItem = lb_itemList.SelectedItem.ToString();
briefPreviewList = Db.getItemBriefPreview(curItem);
string itemInfos = string.Join(",", briefPreviewList.ToArray());
string[] infos = itemInfos.Split(',');
l_itemDB.Text = curItem;
l_CategoryDB.Text = infos[0];
}
private void b_addItem_Click(object sender, EventArgs e)
{
int uid = 1;
AddItem addItemForm = new AddItem(uid);
addItemForm.ShowDialog();
CurrencyManager cm = (CurrencyManager)BindingContext[itemList];
cm.Refresh();
}

I assume when you insert a new item it gets stored into the database, if this is the case then all you need to do is reset the datasource:
private void b_addItem_Click(object sender, EventArgs e)
{
int uid = 1;
AddItem addItemForm = new AddItem(uid);
addItemForm.ShowDialog();
addItemForm.Dispose();
this.showAllItems();
}

Related

Textbox not storing the information and others do if not null of empty

I'm trying to make that theirs a check if a textbox is empty, it wont pass the information on multiple textboxes on a button press, example:
private void button1_Click(object sender, EventArgs e)
{
if (this.Controls.OfType<TextBox>().Any(t => string.IsNullOrWhiteSpace(t.Text)))
{
// what can i put here to exclude multiple
}
else
{
//if any of thouse are empty i dont want them to do this but if they are not empty i do want
lablCinnamonset.Text = textBox1.Text;
lablMallardset.Text = textBox2.Text;
lablAxisdeerSet.Text = textBox3.Text;
lablBlackbuckSet.Text = textBox4.Text;
lablMuledeerSet.Text = textBox5.Text;
lablReddeerSet.Text = textBox6.Text;
lablPumaSet.Text = textBox7.Text;
lablWaterbuffaloSet.Text = textBox8.Text;
lablJackrabbitSet.Text = textBox9.Text;
lablCoyoteSet.Text = textBox10.Text;
lablWhitetailSet.Text = textBox11.Text;
lablBlacktailSet.Text = textBox12.Text;
lablBlackbearSet.Text = textBox13.Text;
lablRooseveltSet.Text = textBox14.Text;
lablMooseSet.Text = textBox15.Text;
}
I don't want to do, a if statement for each textbox, it has to be a better way.
Thank you guys
Why don't just extract a method?
private static void AssignIfNotEmpty(Control target, Control source) {
if (!string.IsNullOrWhiteSpace(source.Text))
target.Text = source.Text;
}
Then use it
private void button1_Click(object sender, EventArgs e) {
AssignIfNotEmpty(lablCinnamonset, textBox1);
AssignIfNotEmpty(lablMallardset, textBox2);
AssignIfNotEmpty(lablAxisdeerSet, textBox3);
AssignIfNotEmpty(lablBlackbuckSet, textBox4);
AssignIfNotEmpty(lablMuledeerSet, textBox5);
AssignIfNotEmpty(lablReddeerSet, textBox6);
AssignIfNotEmpty(lablPumaSet, textBox7);
AssignIfNotEmpty(lablWaterbuffaloSet, textBox8);
AssignIfNotEmpty(lablJackrabbitSet, textBox9);
AssignIfNotEmpty(lablCoyoteSet, textBox10);
AssignIfNotEmpty(lablWhitetailSet, textBox11);
AssignIfNotEmpty(lablBlacktailSet, textBox12);
AssignIfNotEmpty(lablBlackbearSet, textBox13);
AssignIfNotEmpty(lablRooseveltSet, textBox14);
AssignIfNotEmpty(lablMooseSet, textBox15);
}
You may want to organize your controls e.g.
public partial class MyForm : Form {
private Dictionary<Label, TextBox> m_Correspondence =
new Dictionary<Label, TextBox>();
public MyForm() {
InitializeComponent();
m_Correspondence.Add(lablCinnamonset, textBox1);
m_Correspondence.Add(lablMallardset, textBox2);
...
m_Correspondence.Add(lablMooseSet, textBox15);
}
In this case button1_Click will be very simple:
private void button1_Click(object sender, EventArgs e) {
foreach (var pair in m_Correspondence)
AssignIfNotEmpty(pair.Key, pair.Value);
}
Supposing you can change the names of various "labl..." with something like "labl1", "labl2" or mapping them in some way (maybe using a Dictionary), then you can use the
FindName function.
Example:
for(int i=1; i<16; i++){
if( (TextBox)this.FindName("textBox" + i.ToString()).Text != ""){
//Here you can do what you want
}
}
Reference here: https://learn.microsoft.com/it-it/dotnet/api/system.windows.frameworkelement.findname?view=netframework-4.8

Rows adding as many times as page refreshes

I am inserting some content in database on button click event every thing is working fine while insertion of the Data.
The problem is I just refreshed the page after the button click then I noticed that after the button click Data is inserting as many time as I refreshes the page.
How can I stop this ?
Here is my Button Code :
protected void btn_AddEdu_Click(object sender, EventArgs e)
{
hfTab.Value = "edu";
if (ValidateAddEdu())
{
emp_edu.InsertEdu(Session["empcd"].ToString(), ddl_degree.SelectedValue.ToString(), txt_eduterms.Text, ddl_institute.SelectedValue.ToString(), txt_edupassyear.Text, txt_edugrade.Text, ddl_sponsor.SelectedValue.ToString());
int imagefilelength = fileupload_edu.PostedFile.ContentLength;
byte[] imgarray = new byte[imagefilelength];
HttpPostedFile image = fileupload_edu.PostedFile;
image.InputStream.Read(imgarray, 0, imagefilelength);
edu_attach.InsertEduAttachment(Session["empcd"].ToString(),ddl_degree.SelectedValue.ToString(),imgarray);
lbl_eduerr.Text = "Added";
lbl_eduerr.ForeColor = System.Drawing.Color.Green;
BindEduGrid();
}
}
Add following code in your .cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
protected void btn_AddEdu_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
hfTab.Value = "edu";
if (ValidateAddEdu())
{
emp_edu.InsertEdu(Session["empcd"].ToString(), ddl_degree.SelectedValue.ToString(), txt_eduterms.Text, ddl_institute.SelectedValue.ToString(), txt_edupassyear.Text, txt_edugrade.Text, ddl_sponsor.SelectedValue.ToString());
int imagefilelength = fileupload_edu.PostedFile.ContentLength;
byte[] imgarray = new byte[imagefilelength];
HttpPostedFile image = fileupload_edu.PostedFile;
image.InputStream.Read(imgarray, 0, imagefilelength);
edu_attach.InsertEduAttachment(Session["empcd"].ToString(),ddl_degree.SelectedValue.ToString(),imgarray);
lbl_eduerr.Text = "Added";
//Add this line
Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString());
lbl_eduerr.ForeColor = System.Drawing.Color.Green;
BindEduGrid();
}
}
}

Dynamic ImageButton click event not fired

I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
using (ImageButton _btnRemoveEmpleado = new ImageButton())
{
_btnRemoveEmpleado.ID = "btnOffice_1";
_btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
_btnRemoveEmpleado.Height = 15;
_btnRemoveEmpleado.Width = 15;
_btnRemoveEmpleado.ImageUrl = "cross-icon.png";
_btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);
this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}
}
void _btnRemoveEmpleado_Click(object sender, ImageClickEventArgs e)
{
try
{
string s = "";
}
catch (Exception ex)
{
}
finally { }
}
When I click on _btnRemoveEmpleado, the postback is executed but I never reach the string s = ""; line. How could I execute the _btnRemoveEmpleado_Click code, please?
Remove the using, controls are disposed automatically by ASP.NET, they have to live until the end of the page's lifecycle. Apart from that create your dynamic control in Page_Init, then it should work.
protected void Page_Init(object sender, EventArgs e)
{
ImageButton _btnRemoveEmpleado = new ImageButton();
_btnRemoveEmpleado.ID = "btnOffice_1";
_btnRemoveEmpleado.CommandArgument = Guid.NewGuid().ToString();
_btnRemoveEmpleado.Height = 15;
_btnRemoveEmpleado.Width = 15;
_btnRemoveEmpleado.ImageUrl = "cross-icon.png";
_btnRemoveEmpleado.Click += new ImageClickEventHandler(_btnRemoveEmpleado_Click);
this.phPartesPersonal.Controls.Add(_btnRemoveEmpleado);
}

SubmitChanges() not work when i change datagridview

nothing happen and nothing change when I use datagridview and SubmitChanges()
private void Form1_Load(object sender, EventArgs e)
{
this.book_infoDataGridView.DataSource = bookstore.book_info;
BindingSource bds=new BindingSource();
bds.DataSource = this.bookstore.book_info;
this.book_infoBindingSource = bds;
this.book_infobindingNavigator.BindingSource = bds;
}
private void save_Click(object sender, EventArgs e)
{
this.book_infoBindingSource.EndEdit();
bookstore.SubmitChanges();
}
I believe you're trying to .SubmitChanges() from your data in the DataGridView
private void save_Click(object sender, EventArgs e)
{
using (var bookstoreContext = new yourContext())
{
var b = (BookClass)bds.Current;
var book = bookstoreContext.Products.Single(c => c.BookId == b.BookId); //or .First()
book.BookName = b.BookName;
book.BookInfo = b.BookInfo;
bookstoreContext.SubmitChanges();
}
}

Add, Edit, Remove items from a List<String>

I have a list of Strings, List<String>.
I want to be able to open a form, showing the contents of this list, and allow the user to add, edit, and remove items from the list during run time.
I've been looking at ListView, but it isn't clicking for me. I'm not sure if that's because it isn't the right solution or that I don't get it.
What is the proper solution for what I want to do?
Chuck
You can use a list view and a context menu for your target:
try this code:
List<string> listofstring = new List<string>() {"A","B","C" };
private void Form1_Load(object sender, EventArgs e)
{
FillLstView();
}
private void Additem_Click(object sender, EventArgs e)
{
listofstring.Add("New Item");
FillLstView();
}
private void RemoveItem_Click(object sender, EventArgs e)
{
listofstring.RemoveAt(lstview.FocusedItem.Index);
EditItem.Enabled = false;
RemoveItem.Enabled = false;
FillLstView();
}
private void lstview_SelectedIndexChanged(object sender, EventArgs e)
{
RemoveItem.Enabled = true;
EditItem.Enabled = true;
}
private void EditItem_Click(object sender, EventArgs e)
{
string input = Microsoft.VisualBasic.Interaction.InputBox("Enter Edit", "Title", "Edited", 0, 0);
if (input != "")
{
listofstring[lstview.FocusedItem.Index] = input;
EditItem.Enabled = false;
RemoveItem.Enabled = false;
FillLstView();
}
}
private void FillLstView()
{
lstview.Clear();
foreach (var item in listofstring)
{
lstview.Items.Add(item);
}
}
Result
Download Project

Categories