I have stored some number data under column name Value in the tblV table of my database. I want to put the data from that column Value into textbox1.
But whenever I click the button it shows Column 'Value' does not belong to table error even though there is column Value in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
public DataTable GetMaxno(decimal Licenseno)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
string sql = "select Max(Value) from tblv where Licenseno=#licenseno";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Licenseno",Licenseno );
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
da.Fill(DT);
return DT;
}
tryv tv = new tryv();
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
if (dt.Rows.Count > 0)
{
textBox1.Text= dt.Rows[0]["Value"].ToString();
}
}
Reason might be that your query does not return any aliases as Value. You can solve this with select Max(Value) as Value but instead of that, use ExecuteScalar instead which is exactly what you want. It returns first column of the first row.
A few things more;
Use using statement to dispose your connection and command.
Do not use AddWithValue. It may generate unexpected and surprising result sometimes. Use Add method overloads to specify your parameter type and it's size.
public int GetMaxno(decimal Licenseno)
{
using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select Max(Value) from tblv where Licenseno = #licenseno";
cmd.Parameters.Add("#licenseno", SqlDbType.Decimal).Value = Licenseno;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
try
string sql = "select Max(Value) as Value from tblv where Licenseno=#licenseno";
Related
I have this code:
private void FirmaEkleB_Click(object sender, EventArgs e)
{
string query = "INSERT INTO FIRMATABLE VALUES (#CompanyName)";
SqlConnection sqlconnection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, sqlconnection);
Form1 LoginForm = new Form1();
sqlconnection.Open();
command.Parameters.AddWithValue("#CompanyName", FirmaIsmiTextbox.Text);
command.ExecuteScalar();
SqlCommand com2 = new SqlCommand("Select FirmaIsmi FROM FIRMATABLE WHERE ID = 9", sqlconnection);
MessageBox.Show(com2.ExecuteScalar().ToString());
LoginForm.fillFirmaList();
}
fillFirmaList() looks like this:
public void fillFirmaList()
{
connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand("SELECT * FROM FirmaTable", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable firmaTable = new DataTable();
adapter.Fill(firmaTable);
FirmaCombo.DataSource = firmaTable;
FirmaCombo.DisplayMember = "FirmaIsmi";
FirmaCombo.ValueMember = "Id";
}
I don't know what I'm doing wrong but I can't seem get my combobox to update from the table I have. The manually added rows show up but not the one that I add
Keep in mind that I'm just starting out in SQL Server and database stuff.
If more info is needed tell me.
Change your Insert query to
INSERT INTO FIRMATABLE (FirmaIsmi) VALUES (#CompanyName)
You need to include all your column names for which you are adding the VALUES.
And
change ExecuteScalar to command.ExecuteNonQuery().
Add try-catch block and see what exception does it throws after ExecuteNonQuery
I’ve two comboboxes which should contain two different informations.
1.cb1: select table_name from information_schema.tables (this display multiple tables)
2.cb2: should populate it with a column name.
Example: I've three tables in cb1 with the same attributes but have different values at the column EmpName (tblLondon,tblBerlin,tblRom,...)
Now I wanna display in second comboboxe the column EmpName dynamically whenever I choose a table in first combobox.
cb1[tblLondon] cb2[John,Mavis,Chris,Mike..]
OR
cb1[tblBerlin] cb2[Günther,Peter, Sophie,Sunny, ..]
Can u plz help me out
string C = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES ORDER BY TABLE_NAME ASC");
try
{
// Open connection, Save the results in the DT and execute the spProc & fill it in the DT
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
cbTbl.DisplayMember = "TABLE_NAME";
cbTbl.ValueMember = "TABLE_NAME";
//Fill combobox with data in DT
cbTbl.DataSource = dt;
// Empty bzw. clear the combobox
cbTbl.SelectedIndex = -1;
This code is working and populating my cb1 (combobox)
And now i don't really know how to go about with cb2
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
if I understand you correctly, and if you have this data in SQL server or other database you should use SelectedIndexChange event and load item for that Id (use Display Member and Value Member for match Id).
take a look at this.it might help you
Edit :
you can do this with below code : (if you don't use database)
you should use this code in cb1.SelectedIndexChange (or value)
var cb2items = new Dictionary<int, string> {{1, "Name"}, {1, "anotherName"},{2,"Name"},{2, "anotherName"}}; // use the number for parent Id in cb1
foreach (var item in cb2items)
{
if (item.Key == int.Parse(comboBox1.SelectedValue.ToString()))
{
comboBox2.Items.Add(item);
}
}
Edit 2 :
use this code in cb1.SelectedValueChange:
string C = ConfigurationManager.ConnectionStrings[""].ConnectionString;
SqlConnection con = new SqlConnection(C);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("SELECT ... WHERE TableName = cb1.SelectedValue");
spProc & fill it in the DT
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
dt = new DataTable();
adapter.Fill(dt);
cbTbl.DisplayMember = "TABLE_NAME";
cbTbl.ValueMember = "TABLE_NAME";
cbTb2.DataSource = dt;
and you also can create a procedure that send back the items from table name as input. if you use procedure, your code perform better.
Edit 3 :
put this code in cbTb2.SelectedValueChange event :
try
{
int a = int.Parse(cbTB2.SelectedValue.ToString());
}
catch { }
You might want to see combobox's events, "SelectedIndexChanged" or "SelectedValueChanged" should do it
I have two methods, one to insert, update and delete and a second is checking whether data already exists in my database or not. The main purpose of all code is that I don't want to insert duplicate data into the database.
public class DAL : System.Web.UI.Page
{
SqlConnection connection;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public int numofrows;
//Connection Method
public void Connection()
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
}
//This Method will Insert,Update and Delete in Database
public void InsertUpdateDelete(string query)
{
////connection = new SqlConnection("Data Source=IM-82B70624D72D;Initial Catalog=AppointmentScheduler;User ID=sa;Password=za3452432760za");
//connection = new SqlConnection(connectionString);
//connection.Open();
this.Connection();
cmd = new SqlCommand(query, connection);
numofrows = cmd.ExecuteNonQuery();
connection.Close();
}
//This Method will read data From Database
public DataTable ReadData(string Query)
{
this.Connection();
da = new SqlDataAdapter(Query, connection);
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Data already Exist");
}
return dt;
}
}
I have to use both above code in index.aspx. How can I use both above code in index.aspx?
I tried to use but that is not working.
index.aspx code:
protected void btnSaveDays_Click(object sender, EventArgs e)
{
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id='" + DropDownListDays.SelectedValue + "'";
dal.ReadData(this.query);
this.query = "INSERT INTO Dayss VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
dal.InsertUpdateDelete(this.query);
Response.Write("Day Inserted Successfully");
}
But this code is not working and generating error
Conversion failed
not Day_Id is int, and Dayss have two columns. One is id and second is
name
Then there is no point to use single quotes with int typed column value. Single quotes is for character column values.
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id = " + DropDownListDays.SelectedValue ;
And if you want to insert just one column, you need specify your column name in your Dayss table like;
this.query = "INSERT INTO Dayss (YourColumnName) VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
Take a look INSERT (Transact-SQL)
I am trying to delete selected data from datagrid and database at the same time when user clicks on "Delete". It is not working and error message shows that "Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
Can anyone help me out this coding.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
Instead of Remove you can rebind grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
and for deletion ExecuteNonQuery is used:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
Unless you have two rows selected referencing the SelectedRows[1] is wrong. The array indexes start always with zero. (Probably it is just a type because the other lines references correctly the row to be deleted)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
but then, to delete the row in the database, you don't need to use an SqlDataAdapter.
You could work directly with a SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("#iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
finally you could simply remove the selected row from the grid without further query
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
If do not use sql parameters then use plain sql query.
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
I am pulling data from a sql server and putting it into a grid using c#. When the data displays on the grid, it is showing up as the guid rather than the actual name. How do I get the name to show and not the uniqe identifier. Any ideas? Thanks.
Here is some of the code:
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter("select * from Item", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "Item");
dgDataView.DataContext = ds;
//dgDataView.DataMember = "Item";
showdata();
}
}
private void showdata()
{
String connString = "server=server;database=database;user=user;password=password";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Item", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
You are using select * from Item and therefore returning all columns. You could just specify the columns you want in the Grid, in the order you want them. The grid by default has autocolumn generation on.
You can also specify the columns you want and what fields they map to using the columns DataMember values.
I figured this out, I just wrote my own query to display certain columns instead of automatically showing all of them.