Can't add to database with C# and ADO.NET - c#

I want to write a program that save all the data from a .csv into a database.
I use a service-based database.
But when I want to use the addtoTablesName like what I used to do and I learned at university, it suddenly throws an error.
This is my code:
class Program
{
static void Main(string[] args)
{
Database1Entities1 dbb = new Database1Entities1();//object database
excel.Application xlApp;
excel.Workbook xlWb;
excel._Worksheet xlWs;
excel.Range xlRange;
excel.Application xlApp1;
excel.Workbook xlWb1;
excel._Worksheet xlWs1;
excel.Range xlRange1;
int rowFile = 0;
int colFile = 0;
string[][] dataFile;
DateTime date = DateTime.Now;
string tgl = date.Date.ToString("dd");
string bln = date.Month.ToString("d2");
string thn = date.Year.ToString();
string tglskrg = thn+bln+tgl;
string[] items;
DateTime otime2 = DateTime.ParseExact(tglskrg, "yyyyMMdd", null);
xlApp = new excel.Application();
string[] filesindirectory = Directory.GetDirectories(#"C:\Users\u532246\Desktop\TRAVELOKA");
foreach (string files in filesindirectory)
{
string name = Path.GetFileName(files);
string subname = name.Substring(10, 8);
DateTime subTime = DateTime.ParseExact(subname, "yyyyMMdd", null);
TimeSpan span = otime2.Subtract(subTime);
if(span.Days < 2)
{
// Console.WriteLine(files);
foreach(string subfiles in Directory.GetFiles(files))
{
xlWb = xlApp.Workbooks.Open(subfiles);
xlWs = xlWb.Sheets[1];
xlRange = xlWs.UsedRange;
rowFile = xlRange.Rows.Count;
colFile = xlRange.Columns.Count;
dataFile = new string[rowFile][];
for(int i = 0; i < dataFile.Length; i++)
{
dataFile[i] = new string[colFile];
}
for(int i = 0; i<rowFile;i++)
{
for(int j = 0; i<colFile;j++)
{
try
{
dataFile[i][j] = xlWs.Cells[i + 1, j + 1].value2.ToString();
//MessageBox.Show(dataMapping[i][j]);
}
catch (Exception ee)
{
dataFile[i][j] = "";
}
}
}
CMRTable cmr = new CMRTable();
for(int i = 0; i < rowFile; i++)
{
items = dataFile[i][0].Split(';');
cmr.Id = i + 1;
cmr.Merchant_Name = items[1];
cmr.Sett_Date = items[2];
cmr.Proc_Date = items[3];
cmr.Mid = items[4];
cmr.CardType = items[5];
cmr.Trx_Date = items[6];
cmr.Jam_Trx = items[7];
cmr.Auth = items[8];
cmr.CardNo = items[9];
cmr.Trx_Type = items[10];
cmr.Amount = items[11];
cmr.Rate = items[12];
cmr.Disc_Amt = items[13];
cmr.Tenor_Ins = items[14];
cmr.Rate_Ins = items[15];
cmr.Disc_Ins = items[16];
cmr.Net_Amt = items[17];
cmr.Purchase_Id = items[18];
cmr.Mechant_Descriptor = items[19];
dbb.AddToCMRTables(cmr); #I CANT USE THIS FUNCTION , DONT KNOW WHY
dbb.SaveChanges();
}
Console.WriteLine(subfiles);
}
}
}
}
}
Can someone help me? I think I already do everything exactly like I did in university ..
EDIT: here's the error I get:
Database1Entities1 does not contain a definition for AddToCMRTables and no accessible extension method AddToCMRTables accepting a first argument of type Database1Entities1 could be found
I copy what i used to do in university (here's the code)
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
{//dipakai ketika ingin menginsert data ke database.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displayData();
}
Database1Entities db = new Database1Entities();//object database
private void displayData()
{
var query = from x
in db.MsStudents
select x;
dataGridView1.DataSource = query;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
txtID.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString();
txtName.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}//buat ngeklik yg ada di data grid view
private void txtSearch_TextChanged(object sender, EventArgs e)
{
search(txtSearch.Text);
}
public void search(string kata) {
var query = from x
in db.MsStudents
where x.Name.Contains(kata)//apa yang muncul di kotak search itu di select
select x;
dataGridView1.DataSource = query;
}//function buat search
private void btnInsert_Click(object sender, EventArgs e)
{
MsStudent student = new MsStudent();
student.ID = Int32.Parse(txtID.Text);
student.Name = txtName.Text;
db.AddToMsStudents(student);
db.SaveChanges();
displayData();
}
private void btnReset_Click(object sender, EventArgs e)
{
foreach (Control a in this.Controls)
{
if (a.GetType() == typeof(TextBox))
{
a.Text = "";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

Related

Cant write any data into my SQLite database

private void comboBox9_SelectedIndexChanged(object sender, EventArgs e)
{
finish_day = Convert.ToInt32(comboBox9.Text);
}
private void comboBox10_SelectedIndexChanged(object sender, EventArgs e)
{
finish_month = Convert.ToInt32(comboBox10.Text);
}
private void comboBox11_SelectedIndexChanged(object sender, EventArgs e)
{
finfish_year = Convert.ToInt32(comboBox11.Text);
}
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
begin_year = Convert.ToInt32(comboBox6.Text);
}
private void comboBox7_SelectedIndexChanged(object sender, EventArgs e)
{
begin_month = Convert.ToInt32(comboBox7.Text);
}
private void comboBox8_SelectedIndexChanged(object sender, EventArgs e)
{
begin_day = Convert.ToInt32(comboBox8.Text);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_bs_2 += serialPort1.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata));
Thread.Sleep(1000);
}
private void showdata(object sender, EventArgs e)
{
int changdu = from_bs_2.Length;
if (changdu > 50)
{
chushihua++;
string fro;
string[] parm = new string[6];
textBox1.Text += from_bs_2;
fro = from_bs_2;
parm = fro.Split('\n');
string path = "C:\\Users\\COM\\Desktop\\data_logging.txt";
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
for (int a = 0; a < 4; a++)
{
string[] zhongjian = new string[23];
zhongjian = parm[a].Split(';');
// textBox1.Text += zhongjian;
for (int keai = 0; keai < 23; keai++)
{
current[a, keai] = Convert.ToDouble(zhongjian[keai]);
sw.Write(current[a, keai]); sw.Write(';');
}
sw.WriteLine('/');
}
string[] zhongjian_2 = new string[23];
zhongjian_2 = parm[5].Split(';');
for (int m = 0; m < 23; m++) //
{
volatge[m] = Convert.ToDouble(zhongjian_2[m]);
sw.Write(volatge[m]); sw.Write(';');
}
sw.WriteLine('/');
DateTime dt = DateTime.Now; //strong text
int y = dt.Year; //
int yue = dt.Month; //
int d = dt.Day; //
int h = dt.Hour; //
int n = dt.Minute; //
textBox1.Text += y;
textBox1.Text += "-";
textBox1.Text += yue;
textBox1.Text += "-";
textBox1.Text += d;
textBox1.Text += "-";
textBox1.Text += h;
textBox1.Text += ":";
textBox1.Text += n;
textBox1.Text += "-";
textBox1.Text += "data logging times";
textBox1.Text += chushihua;
sw.Write(y); sw.Write("-"); sw.Write(yue); sw.Write("-"); sw.Write(d);
sw.Write("-"); sw.Write(h); sw.Write(":"); sw.Write(n); sw.WriteLine('/');
sw.Close();
fs.Close();
//////////////////time/////////////////////////////
string info = "INSERT INTO Logging_Data_2 (Time,Number,Power1,Power2,Power3,Power4,Power5,Power6,Power7,Power8,Power9,Power10,Power11,Power,Power12,Power13,Power14,Power15,Power16,Power17,Power18,Power19,Power20,Power21,Power22,Power23) values ('a',1,current[0, 0],current[0, 1],current[0, 2],current[0, 3],current[0, 4],current[0, 5],current[0, 6],current[0, 7],current[0, 8],current[0, 9],current[0, 10],current[0, 11],current[0, 12],current[0, 13],current[0, 14],current[0, 15],current[0, 16],current[0, 17],current[0, 18],current[0, 19],current[0, 20],current[0, 21],current[0, 22])";
using (System.Data.SQLite.SQLiteConnection connection = new System.Data.SQLite.SQLiteConnection("data source=logging_data.db"))
{
// connection.Open();
// using (DbTransaction transaction = connection.BeginTransaction())
// {
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(connection))
{
connection.Open();
command.CommandText = info;
//*emphasized text*command.ExecuteNonQuery();
}
// transaction.Commit();
// }
}
from_bs_2 = "";
if (textBox1.Text.Length > 1500)
{
textBox1.Text = "";
}
}
}
I am wirting a super simple file, get the data from arduino though serial ports, and than if i get data, first i log them in a txt file, and then I need to send them into a database for future calculation. therefore I installed the SQLite, and write caode in this, but when i test it, I can log data to txt fime, but nothing in my database.
I set up a database named logging_data, and the table is Logging_data_2, when I find I cant log any data to database, i just let the time be 'a', number be 1,but it still doesnt work. ask for help, thankyou!

TweetInvi Listview can't get TweetID

I'm trying to get Tweet ID via TweetInvi API but always get null point exception. I'm out of options and can't understand what i did wrong. Here is my code. Problem occurs when i select desired Item from view and press retweet.
namespace MIF_TwitterApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Auth.SetUserCredentials("KEY", "KEY", "KEY",
"KEY");
}
private void Form1_Load(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
//PROFILE
profileImage.ImageLocation = user.ProfileImageUrlFullSize;
nameLabel.Text = user.Name;
usernameLabel.Text = "#" + user.ScreenName;
followersLabel.Text = "Followers: " + user.FollowersCount;
}
//Tweeting with PICS
private void tweetBtn_Click(object sender, EventArgs e)
{
if (tweetBox.Text != "")
{
if (imgUploadPath.Text != "")
{
byte[] file = File.ReadAllBytes(imgPreview.ImageLocation);
Tweet.PublishTweetWithImage(tweetBox.Text, file);
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
tweetBox.Clear();
MessageBox.Show("Tweet posted!");
}
else
{
Tweet.PublishTweet(tweetBox.Text);
MessageBox.Show("Tweet posted!");
tweetBox.Clear();
}
}
else
{
MessageBox.Show("Please enter text!");
tweetBox.Clear();
}
}
private void addImg_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
imgPreview.ImageLocation = ofd.FileName;
imgUploadPath.Text = ofd.FileName;
}
private void dropImg_Click(object sender, EventArgs e)
{
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
}
private void timelineBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetHomeTimeline(40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void postsBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetUserTimeline(user, 40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void retweetBtn_Click(object sender, EventArgs e)
{
var checkedItems = listView1.SelectedItems;
long a = (long)listView1.SelectedItems[0].Tag;
var user = User.GetAuthenticatedUser();
var retweet = Tweet.PublishRetweet(a);
MessageBox.Show("Retweet was successfull");
listView1.Items.Clear();
}
}
}
Breakes on long a, I can't figure out how to get that Long Tweet ID
Here is the full code
Problem was that my X was not incrementing correctly as it was out of for loop.
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
x = x +1;
}

Regarding strongly typed dataset in windows form application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.

Web form is not updating values

I am trying to save retrieve and update data table from s single web form. Data is saved and retrieve correctly but is not updated.
Here is the code
using System;
using System.Web.UI;
using System.Data;
public partial class Basic_Information : System.Web.UI.Page
{
DataTable user_dt, personal_dt = new DataTable();
string u_id;
Boolean check = false;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
if (Session["user"] != null)
load();
}
protected void btn_save_Click(object sender, EventArgs e)
{
if(check == false)
savedata();
else
editdata();
}
protected void load()
{
user_dt = (DataTable)Session["user"];
u_id = user_dt.Rows[0][0].ToString();
personal_dt = (DataTable)Session["personal"];
if (personal_dt.Rows.Count != 0)
{
retrivedata();
check = true;
}
}
protected void savedata()
{
personal_dt.Columns.Add("User_id");
personal_dt.Columns.Add("Name");
personal_dt.Columns.Add("Father_Name");
personal_dt.Columns.Add("CNIC");
personal_dt.Columns.Add("Date_of_Birth");
personal_dt.Columns.Add("Domicile");
personal_dt.Columns.Add("Gender");
personal_dt.Columns.Add("Religion");
personal_dt.Columns.Add("Nationality");
personal_dt.Columns.Add("Marital");
DataRow per_row = personal_dt.NewRow();
per_row["User_id"] = u_id;
per_row["Name"] = txt_name.Text;
per_row["Father_Name"] = txt_fname.Text;
per_row["CNIC"] = txt_cnic.Text;
per_row["Date_of_Birth"] = txt_dofb.Text;
per_row["Domicile"] = ddl_domicil.SelectedItem.Text;
per_row["Gender"] = ddl_gender.SelectedItem.Text;
per_row["Religion"] = ddl_religion.SelectedItem.Text;
per_row["Nationality"] = txt_nationality.Text;
per_row["Marital"] = ddl_marital.SelectedItem.Text;
personal_dt.Rows.Add(per_row);
string script = "alert('Profile Successfully Saved');";
ClientScript.RegisterStartupScript(this.GetType(), "saved", script, true);
}
}
protected void retrivedata()
{
txt_name.Text = personal_dt.Rows[0]["Name"].ToString();
txt_fname.Text = personal_dt.Rows[0]["Father_Name"].ToString();
txt_cnic.Text = personal_dt.Rows[0]["CNIC"].ToString();
txt_dofb.Text = personal_dt.Rows[0]["Date_of_Birth"].ToString();
ddl_domicil.Items.FindByText(personal_dt.Rows[0] ["Domicile"].ToString()).Selected = true;
ddl_gender.Items.FindByText(personal_dt.Rows[0]["Gender"].ToString()).Selected = true;
ddl_religion.Items.FindByText(personal_dt.Rows[0]["Religion"].ToString()).Selected = true;
txt_nationality.Text = personal_dt.Rows[0]["Nationality"].ToString();
ddl_marital.Items.FindByText(personal_dt.Rows[0]["Marital"].ToString()).Selected = true;
}
protected void editdata()
{
personal_dt.Rows[0]["Name"] = txt_name.Text;
personal_dt.Rows[0]["Father_Name"] = txt_fname.Text;
personal_dt.Rows[0]["CNIC"] = txt_cnic.Text;
personal_dt.Rows[0]["Date_of_Birth"] = txt_dofb.Text;
personal_dt.Rows[0]["Domicile"] = ddl_domicil.SelectedItem.Text;
personal_dt.Rows[0]["Gender"] = ddl_gender.SelectedItem.Text;
personal_dt.Rows[0]["Religion"] = ddl_religion.SelectedItem.Text;
personal_dt.Rows[0]["Nationality"] = txt_nationality.Text;
personal_dt.Rows[0]["Marital"] = ddl_marital.SelectedItem.Text;
}
}
Saving data correctly, retrieving data correctly.
But bug in editing data return the first values which are retrieved.
Also an error that Dropdown cannot select multiple items
Regarding dropdown binding issue, before
Dropdown.DataSource = YourDataSource
add
Dropdown.ClearSelection();
Try this.After filling data to datatable you need to pass that datatable, and update record.
protected void editdata()
{
DataRow dr = personal_dt.NewRow();
personal_dt.Rows.Add(dr);
dr["Name"] = txt_name.Text;
dr["Father_Name"] = txt_fname.Text;
dr["CNIC"] = txt_cnic.Text;
dr["Date_of_Birth"] = txt_dofb.Text;
dr["Domicile"] = ddl_domicil.SelectedItem.Text;
dr["Gender"] = ddl_gender.SelectedItem.Text;
dr["Religion"] = ddl_religion.SelectedItem.Text;
dr["Nationality"] = txt_nationality.Text;
dr["Marital"] = ddl_marital.SelectedItem.Text;
}

How can I save the path of an image in OpenFileDialog to a string?

I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
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;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}

Categories