i'm creating a system that has an add-edit-delete function but whenever i try to edit a value from my ms sql server 2005 it keeps on telling me "cannot find table 0". below is my code i'm using visual studio c# 2008:
private void button2_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter dad = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(dad);
dad.UpdateCommand = new SqlCommand("UPDATE tblSchools SET Number = #id, School_Name = #school, Province = #prov, City = #city, Brgy = #brgy, Lot_Num = #lot, Area = #area, Mem_Date_Rec = #date, Cenro = #cenro", conn);
dad.UpdateCommand.Parameters.Add("#school", SqlDbType.VarChar).Value = textBox1.Text;
dad.UpdateCommand.Parameters.Add("#prov", SqlDbType.VarChar).Value = comboBox1.Text;
dad.UpdateCommand.Parameters.Add("#city", SqlDbType.VarChar).Value = textBox2.Text;
dad.UpdateCommand.Parameters.Add("#brgy", SqlDbType.VarChar).Value = textBox4.Text;
dad.UpdateCommand.Parameters.Add("#lot", SqlDbType.NVarChar).Value = textBox5.Text;
dad.UpdateCommand.Parameters.Add("#area", SqlDbType.Decimal).Value = textBox6.Text;
dad.UpdateCommand.Parameters.Add("#date", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
dad.UpdateCommand.Parameters.Add("#cenro", SqlDbType.NVarChar).Value = textBox8.Text;
dad.UpdateCommand.Parameters.Add("#id", SqlDbType.Int).Value = ds.Tables[0].Rows[tblNamesBS.Position][0];
conn.Open();
dad.UpdateCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
above the code i made a global function
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True");
BindingSource tblNamesBS = new BindingSource();
what seems to be the problem here??
oh and to add up i made a datagridview that has a double click event, below is my code:
private void dg_DoubleClick(object sender, EventArgs e)
{
try
{
button2.Visible = true;
button5.Visible = true;
DataTable dt = new DataTable();
SqlDataAdapter dad = new SqlDataAdapter("SELECT * FROM tblSchools WHERE Number ="+
Convert.ToInt16(dg.SelectedRows[0].Cells[0].Value.ToString()) + "", conn);
dad.Fill(dt);
textBox1.Text = dt.Rows[0][1].ToString();
comboBox1.Text = dt.Rows[0][2].ToString();
textBox2.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
//dateTimePicker1.Value = dt.Rows[0][7];
textBox8.Text = dt.Rows[0][8].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
will this code affect my edit?
You have declared an empty data set
DataSet ds = new DataSet();
And later you try to access Table[0] in it but there isn't one defined.
Related
I have a single SQlite query that returns "10" to me but I couldn't send it to c# textbox1.text area. I found datagrid examples which work just fine but single value for textbox I could not handle it.
I tried changing datagrid areas to textbox but really I have no idea how to get value with sqlite
private SQLiteConnection con = new SQLiteConnection();
private SQLiteCommand com = new SQLiteCommand();
private SQLiteDataAdapter adapt = new SQLiteDataAdapter();
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
//private SQLiteDataReader dr = new SQLiteDataReader();
public void set_connection()
{
con = new SQLiteConnection();
con.ConnectionString = ("Data Source=data/lastix_db.s3db");
}
public void execute_q(string txtQuery)
{
set_connection();
con.Open();
com = con.CreateCommand();
com.CommandText = txtQuery;
com.ExecuteNonQuery();
con.Close();
}
public void load_data()
{
set_connection();
con.Open();
com = con.CreateCommand();
string comtext = "SELECT * FROM stok";
adapt = new SQLiteDataAdapter(comtext, con);
ds.Reset();
adapt.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
con.Close();
}
private void Button2_Click(object sender, EventArgs e)
{
set_connection();
string stokout = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
execute_q(stokout);
label16.Text = Convert.ToString(stokout);
label16.Text = //must be read "10" from sqlite
Insert update delete and all other datagrid solutions are ok but I'm really stuck on read single data and type it to textbox.
SQLiteConnection connect = new SQLiteConnection();
connect.ConnectionString = ("Data Source=data/lastix_db.s3db");
connect.Open();
string sql = "SELECT SUM(giris_adet) - SUM(cikis_adet) as mevcutstok from stok where malzeme_kodu = 651";
SQLiteCommand cmd = new SQLiteCommand(sql, connect);
Int32 totalp = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
baglan.Close();
//MessageBox.Show("Your Balance is: " + totalp);
label16.Text = Convert.ToString(totalp);
This is my code. After adding data through DataSource, The SelectedIndexChanged event is not firing.
try
{
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//comboBox1.Items.Clear();
comboBox1.ResetText();
Cn.Open();
SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
SqlDataReader da = Cd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
dt.Load(da);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
}
finally
{
Cn.Close();
Clear();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Label CBSL = new Label();
//string CBSL = this.comboBox1.SelectedItem.ToString();
if (comboBox9.Text == "Client")
{
Update_Read_Client();
}
else if (comboBox9.Text == "Customer")
{
Update_Read();
}
}
It selects the first value again and again.
I had tried DropDownStye = DropDownList., But it become dormant. No values is added.
Any help to resolve my problem.
I'm not sure if you have "< Select >" item saved in your database. Also, when using DataTable it's easier to fill it using SqlDataAdapter. You should also use parameters instead of string concat when you're writing your query like this and using keyword closes your connection automatically when you're done using it. I'd write it like this probably:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT DISTINCT Mobile
FROM Client_Details
WHERE Branch = #Branch";
cmd.Parameters.AddWithValue("#Branch", label2.Text);
try
{
var dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataRow row = dt.NewRow();
row["Mobile"] = "<Select>";
dt.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
throw;
}
}
I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}
When I fill the registration form and click on the button to move to user panel it does not move to the user panel, it freezes on the registration. In the user panel code behind it shows this message:
Object reference not set to an instance of an object.
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email,Country, State,City, Post, Img, Logo,RegDate) VALUES (#UID,#FN,#LN,#Password,#RePass,#Email,#Country,#State,#City,#Post,#Img,#Logo,#RegDate)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#UID", UsrNme.Text);
cmd.Parameters.AddWithValue("#FN", fnbox.Text);
cmd.Parameters.AddWithValue("#LN", lnamebox.Text);
cmd.Parameters.AddWithValue("#Password", passtxtbx1.Text);
cmd.Parameters.AddWithValue("#RePass", passtxtbx2.Text);
cmd.Parameters.AddWithValue("#Email", emailbox.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Post", postbox.Text);
cmd.Parameters.AddWithValue("#Img", persimgFileUpload1.FileName);
cmd.Parameters.AddWithValue("#Logo", logoFileUpload.FileName);
//Get the Current Date Time here
cmd.Parameters.AddWithValue("#RegDate", DateTime.Now);
if (!string.IsNullOrEmpty(UsrNme.Text))
{
Lblcheckusername.Text = "User Name Already Exist";
Lblcheckusername.ForeColor = System.Drawing.Color.Red;
}
else
{
Lblcheckusername.Text = "User Name Available";
Lblcheckusername.ForeColor = System.Drawing.Color.Green;
}
if (persimgFileUpload1.HasFile)
{
persimgFileUpload1.SaveAs(Server.MapPath("~/images/users/" + persimgFileUpload1.FileName));
}
if (logoFileUpload.HasFile)
{
logoFileUpload.SaveAs(Server.MapPath("~/images/Logos/" + logoFileUpload.FileName));
}
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
Here is the user panel codebehind where the error appears on the first code line:
USRNMElbl.Text = Session["UsrNme"].ToString();
if (Session["UsrNme"] != null)
{
}
if (!Page.IsPostBack)
{
DataTable countrycascd = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [countryID],[country] FROM [countr]", con);
adaptar.Fill(countrycascd);
countrdrdolst.DataSource = countrycascd;
countrdrdolst.DataTextField = "country";
countrdrdolst.DataValueField = "countryID";
countrdrdolst.DataBind();
}
countrdrdolst.Items.Insert(0, new ListItem("Välj land", "0"));
}
if (!Page.IsPostBack)
{
DataTable Sectiondt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [CateID],[Category] FROM [Section]", con);
adaptar.Fill(Sectiondt);
Catedrdoads.DataSource = Sectiondt;
Catedrdoads.DataTextField = "Category";
Catedrdoads.DataValueField = "CateID";
Catedrdoads.DataBind();
}
Catedrdoads.Items.Insert(0, new ListItem("Select Section", "0"));
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 2;
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 3;
}
protected void addadsbtn_Click(object sender, EventArgs e)
{
Guid newGUID = Guid.NewGuid();
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO [ads] ([Section], [Category], [UID], [AdsTit], [AdsDesc], [Country], [State], [City], [AdsPrice], [Img1], [img2], [img3], [img4], [img5], [Wtags]) VALUES (#Section, #Category, #UID, #AdsTit, #AdsDesc, #Country, #State, #City, #AdsPrice, #Img1, #img2, #img3, #img4, #img5, #Wtags)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#Section", Catedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Category", SubCatedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#UID", USRNMElbl.Text);
cmd.Parameters.AddWithValue("#AdsTit", addadstittxtbx.Text);
//cmd.Parameters.AddWithValue("#AdsDesc", Editor1.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AdsPrice", adsaddpristxtbx.Text);
cmd.Parameters.AddWithValue("#Img1", FileUpload1.FileName);
cmd.Parameters.AddWithValue("#Img2", FileUploadImg2.FileName);
cmd.Parameters.AddWithValue("#Img3", FileUploadImg3.FileName);
cmd.Parameters.AddWithValue("#Img4", FileUploadImg4.FileName);
cmd.Parameters.AddWithValue("#Img5", FileUploadImg5.FileName);
cmd.Parameters.AddWithValue("#Wtags", addadswtagtxtbtn.Text);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
The problem might be your Session["UsrNme"] is null
if (Session["UsrNme"] != null)
{
USRNMElbl.Text = Session["UsrNme"].ToString();
}
else
{
return;
}
You could also read http://www.codingdefined.com/2014/06/object-reference-not-set.html
Running the following code, I find that SelectedIndexChanged method runs before load method... How can I correct this? I tried resetting the events but that didn't work either
namespace adotestquestion
{
public partial class Bill : Form
{
public Bill()
{
InitializeComponent();
}
string constring = "data source=NISHANT-PC ; initial catalog=NIK_DATABASE ; user id=xxxxxx ; password=xxxxxx";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter adapter;
DataSet ds;
DataTable dt;
int qty, tax, total, price;
private void Bill_Load(object sender, EventArgs e)
{
con = new SqlConnection(constring);
cmd = new SqlCommand("select billid from bill", con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "billid";
comboBox1.ValueMember = "billid";
MessageBox.Show(id.ToString());
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(comboBox1.Text);
int id;
id = Convert.ToInt32(comboBox1.Text);
con = new SqlConnection(constring);
cmd = new SqlCommand("select * from bill where billid=#id", con);
// cmd.Parameters.Add("#id", Convert.ToInt32(comboBox1.Text));
cmd.Parameters.Add("#id", id);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
textBox1.Text = dr[1].ToString();
textBox2.Text = dr[2].ToString();
textBox3.Text = dr[4].ToString();
textBox4.Text = dr[3].ToString();
textBox5.Text = dr[5].ToString();
textBox6.Text = dr[6].ToString();
textBox7.Text = dr[7].ToString();
textBox8.Text = dr[8].ToString();
textBox9.Text = dr[9].ToString();
textBox10.Text = dr[10].ToString();
}
}
}
}
Unwire the events subscription in InitializeComponent method and wire it at the end of Form_Load.
Instead of trying to change the events, etc. you can simply check if there is anything in fact selected in the combo box in your event. This will keep the code simple and will work correctly.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex >= 0)
{
// your existing code goes here
}
}
A third alternative is to create a private class-level variable like isFormLoading and set it to true initially, then set it to false at the end of your Bill_Load event.
You can check the value of the variable in comboBox1_SelectedIndexChanged and anywhere else it's needed to determine whether a block of code should run or not.
But really, any of the other provided answers will work.
Problem : whenever you bind an Items to your Combobox , SelectedIndexChanged event will be fired.
Solution : inside the SelectedIndexChanged event you need to identify wether it is fired from the Load event or due to the Item selection change.
you can declare a boolean variable ,set it to true whenever control enters into Load event.
from selectedIndexChanged event only execute the code when boolean variable is false.
Note : at the end of the Load event again change the boolean variable to false so that SelectionChanged event will be fired when actually selection Changes in the ComboBox.
Try This:
bool loadevent = false;
private void Bill_Load(object sender, EventArgs e)
{
loadevent = true;
con = new SqlConnection(constring);
cmd = new SqlCommand("select billid from bill", con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "billid";
comboBox1.ValueMember = "billid";
MessageBox.Show(id.ToString());
loadevent = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!loadevent)
{
MessageBox.Show(comboBox1.Text);
int id;
id = Convert.ToInt32(comboBox1.Text);
con = new SqlConnection(constring);
cmd = new SqlCommand("select * from bill where billid=#id", con);
// cmd.Parameters.Add("#id", Convert.ToInt32(comboBox1.Text));
cmd.Parameters.Add("#id", id);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds);
dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
textBox1.Text = dr[1].ToString();
textBox2.Text = dr[2].ToString();
textBox3.Text = dr[4].ToString();
textBox4.Text = dr[3].ToString();
textBox5.Text = dr[5].ToString();
textBox6.Text = dr[6].ToString();
textBox7.Text = dr[7].ToString();
textBox8.Text = dr[8].ToString();
textBox9.Text = dr[9].ToString();
textBox10.Text = dr[10].ToString();
}
}
}