Why is my entered data not stored in Database? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
public List<TextBox> _textBoxes = new List<TextBox>();
protected void btmSubmit_Click1(object sender, EventArgs e)
{
dbDataItem();
}
public void dbDataItem()
{
dc.cnn.Open();
_textBoxes = getTextBox();
//foreach (TextBox text in _textBoxes)
//{
// _textBoxes.Add(text.Text.Trim());
// //StoreValue(text.Text);
//}
foreach (TextBox textBox in _textBoxes)
{
//TextBox txt = new TextBox();
//txt.ID = Panel2.FindControl("textBox").ToString();
string value = textBox.Text;
string query = "select name from DataItem where name = '" + value + "'";
SqlCommand cmd = new SqlCommand(query, dc.cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
int count = dt.Rows.Count;
if (count == 0)
{
int i = MaxCode1();
SqlCommand cmd2 = new SqlCommand("insert into DataItem (code,name) values (#code,#name)", dc.cnn);
cmd2.Parameters.AddWithValue("#code", i);
cmd2.Parameters.AddWithValue("#name", value);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
dc.cnn.Close();
}
else
{
Response.Write("<script language='javascript'>alert('This DataItem already exist in database');</script>");
}
}
dc.cnn.Close();
}

You don't run cmd2.
After setting Parameters, run it like this :
cm2.ExecuteNonQuery();
So, your code looks like this :
SqlCommand cmd2 = new SqlCommand("insert into DataItem (code,name) values (#code,#name)", dc.cnn);
cmd2.Parameters.AddWithValue("#code", i);
cmd2.Parameters.AddWithValue("#name", value);
cmd2.ExecuteNonQuery();
dc.cnn.Close();

Calling SqlDataAdapter.Fill to execute an INSERT command is not correct. The Fill method is used to retrieve record from the database using a SELECT statement. In your code the INSERT statement is passed as the SelectCommand of the adapter and it is executed when you call Fill so the record is added to your database table. But there is no return value in your DataTable code object because the SelectCommand used by the Fill method has no SELECT statement assigned to it.
You need to split the two actions, first ExecuteNonQuery on the INSERT statement, then create the adapter with the correct SELECT statement
SqlCommand cmd2 = new SqlCommand("insert into DataItem (code,name) values (#code,#name)", dc.cnn);
cmd2.Parameters.AddWithValue("#code", i);
cmd2.Parameters.AddWithValue("#name", value);
cmd2.ExecuteNonQuery()
SqlDataAdapter da2 = new SqlDataAdapter("SELECT * FROM DataItem");
DataTable dt2 = new DataTable();
da2.Fill(dt2);

Related

Get One Column's Data from Db and Set it to multiple Checkboxes in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 months ago.
Improve this question
I have multiple Checkboxes in a page and their values are being stored in one column. Now I want that if I get data from Db then Checkbox is checked if their value is store in that column.
What Store Procedure and C# code I use for this?
Here is my code;
private void SetRoles()
{
SqlCommand cmd2 = new SqlCommand("SPD_GetAllUsersList");
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#id", "ABC01");
SqlDataAdapter sda2 = new SqlDataAdapter();
cmd2.Connection = con;
sda2.SelectCommand = cmd;
DataTable dt2 = new DataTable();
sda2.Fill(dt2);
con.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
bool recfound2 = dr2.Read();
if (recfound2)
{
if (dt2.Columns[0].ToString() == "Add Staff".ToString())
{
CBAddStaff.Checked = true;
}
else
{
CBAddStaff.Checked = false;
}
if (dt2.Columns[0].ToString() == "Update Staff".ToString())
{
CBAUpdateStaff.Checked = true;
}
else
{
CBAUpdateStaff.Checked = false;
}
}
con.Close();
}
There are many things wrong with your peace of code my friend
Your code for reading data from database is too long, and doesn't even make much sense. Try this:
A little tip: read the data in a separate method.
private DataTable ReadRoles()
{
var cmd = new SqlCommand("SPD_GetAllUsersList");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", "ABC01");
var con = new SqlConnection("YourConnectionString");
var sda = new SqlDataAdapter(cmd, con);
var cmb = new SqlCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
return ds.Tables[0];
}
Now we store the returned DataTable in a variable, and search through that:
var Roles = ReadRoles();
CBAddStaff.Checked = false;
CBAUpdateStaff.Checked = false;
foreach (DataRow row in Roles)
{
if (row["RoleId"].ToString() == "Add Staff") CBAddStaff.Checked = true;
else if (row["RoleId"].ToString() == "Update Staff") CBAUpdateStaff.Checked = true;
else continue;
}
Now, if you really need to use all of this in one method, I suggest you create method that does everything in the second piece of code I wrote: Call the ReadRoles(), uncheck both ckechboxes (so you don't need if-else , if-else), and set Checked of the right checkbox to true
Don't forget to vote and accept if you find this helpful

c# function for filling ComboBox

I Want to create a function in ClassProducts.cs file and when I call that function it should return Values & Tags for that ComboBox.
ComboBox Control is in ViewProducts Form and function in ClassProducts.cs class. Function accepts 1 parameter called Cat_ID
class ClassProducts
{
public DataTable FillSubCats(int catID)
{
DataTable items = new DataTable();
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =" + catID, con);
con.Open();
SqlDataReader sda = cmdFillSubCatL1.ExecuteReader();
while (sda.Read())
{
ComboboxItem item = new ComboboxItem();
item.Text = (sda["Cat_Name"]).ToString();
item.Value = (sda["Cat_ID"]).ToString();
items.Load(sda);
}
sda.Dispose();
sda.Close();
con.Close();
return items;
}
}
I want a function in ClassProducts file which will be filling ComboBoxes in ViewProducts.cs Form. Whenever function called it should return combo box items to the calling file.
I have tried this function but it is not working.
Please help.
Thank You.
This is most probably due to the fact that you are not using sqlparameters. Cat_ParentCat must be an int field so when you try to use query with string concatenation, a cats to nvarchar field is taking place, and since you don't wrap catId with quotes on your query, it fails . In any case using SQL Parameters, will also help you avoid SQL injection. Try:
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =#catId", con);
cmdFillSubCatL1.Parameteres.Add("#catId",SqlDbType.Int).Value=catId;
...
EDIT:
After Correct comment, a better query should be:
"SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat =#catId"
Finally since you want to load a DataTable don't use Datareader but a dataAdapter:
...
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmdFillSubCatL1 ;
adapter.Fill(items );
How about this. I have added a method FillSubCatsProxy which should simulate what your method is returning.:
public Form1()
{
InitializeComponent();
comboBox1.DataSource = FillSubCatsProxy(1);
comboBox1.DisplayMember = "Cat_Name";
comboBox1.ValueMember = "Cat_ID";
comboBox1.SelectedIndexChanged += (s, e) => { MessageBox.Show("Selected:" + comboBox1.SelectedValue); };
}
public DataTable FillSubCatsProxy(int catID)
{
var dt = new DataTable();
dt.Columns.Add("Cat_Name");
dt.Columns.Add("Cat_ID");
dt.Rows.Add("Fish","1");
dt.Rows.Add("Jack","2");
return dt;
}
public DataTable FillSubCats(int catID)
{
SqlConnection con = new SqlConnection("Somewhere");
try
{
con.Open();
DataTable items = new DataTable();
var da = new SqlDataAdapter("SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat = " + catID, con);
da.Fill(items);
return items;
}
finally
{
con.Close();
}
}
}

DataAdapter Update issue

The following coding doesn't update my table. But rows variable value is 1 after updating.
I cannot understand what is the cause behind this. Please help.
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
var wktbl = new DataTable();
var cmd = new SqlCommand("SELECT * FROM Test", connection1);
var da1 = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da1);
da1.Fill(wktbl);
wktbl.Rows[0][2] = "5";
da1.UpdateCommand = b.GetUpdateCommand(true);
int rows = da1.Update(wktbl);
Check this page out. It shows the example below of doing an update with the dataadapter.
The following examples demonstrate how to perform updates to modified rows by explicitly setting the UpdateCommand of a DataAdapter and calling its Update method. Notice that the parameter specified in the WHERE clause of the UPDATE statement is set to use the Original value of the SourceColumn. This is important, because the Current value may have been modified and may not match the value in the data source. The Original value is the value that was used to populate the DataTable from the data source.
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
I found the problem. It's because connectionString has |DataDirectory|.
The MDF file location is different when running the application.

How to load a dropdown list box from Mysql database using C# asp.net? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to load the dropdown list box with a column of a table from Mysql in asp.net with C#.
So right now you've noted that you just want to load a single field. That's what the following code would do. It will select a single field, from a single table, and bind it to the combo box.
using (MySqlConnection c = new MySqlConnection(connString))
{
c.Open();
var sql = "SELECT field_name FROM table_name";
using (MySqlCommand cmd = new MySqlCommand(sql, c))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
comboBox.ValueMember = "field_name";
comboBox.DisplayMember = "field_name";
comboBox.DataSource = dt;
}
}
However, I think the more general use of it might be something like this:
using (MySqlConnection c = new MySqlConnection(connString))
{
c.Open();
var sql = "SELECT key_field, display_field FROM table_name";
using (MySqlCommand cmd = new MySqlCommand(sql, c))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
comboBox.ValueMember = "key_field";
comboBox.DisplayMember = "display_field";
comboBox.DataSource = dt;
}
}
Here you're listing data and have both a key_field and a display_field. The importance of that is generally combo boxes are used for lookup type data. Either way, when you wanted to get the value of the combo box, use the SelectedValue member.
comboBox.SelectedValue
Welcome to the Stackoverflow:)
Please refer below code snippet for your requiremrnt:
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id FROM Customers";
using (var command = new MySqlCommand(query, connection))
{
using (var reader = command.ExecuteReader())
{
//Iterate through the rows and add it to the combobox's items
while (reader.Read())
{
CustomerIdComboBox.Items.Add(reader.GetString("Id"));
}
}
}
}
string str="Select km from tablename;
SqlDataAdapter ad = new SqlDataAdapter(str,connection object);
DataSet ds = new DataSet();
ad.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
Textbox1.Text = ds.Tables[0].Rows[0][0].ToString();
}

I want to create a command that will compute fine for specific person [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a command that will compute for overdue books but I want it in specific person only.
My command is to insert fine in the table Borrowbook. I also put the codes in the button where datagridview will show data.
My code is like this:
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Student ID], ISBN, Title, Date, [Due Date], Penalty FROM Borrowbook;", con);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable Records = new DataTable();
sda.Fill(Records);
BindingSource bsource = new BindingSource();
bsource.DataSource = Records;
dataGridView1.DataSource = bsource;
sda.Update(Records);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (dateTimePicker2.Value < DateTime.Now)
{
cmd.CommandText = "INSERT INTO Borrowbook (Penalty) VALUES (#Penalty)";
SqlParameter p1 = new SqlParameter("#Penalty", SqlDbType.Int);
p1.Value = 50;
cmd.Parameters.Add(p1);
cmd.ExecuteNonQuery();
Your command to UPDATE the borrow record (it is already present in the table) with the fine should include the Student ID and the ISBN of the books with overdue return
cmd.CommandText = "UPDATE Borrowbook SET Penalty = #Penalty " +
"WHERE [Student ID] = #stuid AND ISBN = #isbn";
cmd.Parameters.AddWithValue("#Penalty", 50);
cmd.Parameters.AddWithValue("#stuid", GetStudentID());
cmd.Parameters.AddWithValue("#isbn", GetISBN());
cmd.ExecuteNonQuery();
Of course you need to extract the values for the parameter Student ID and the ISBN from your grid (I suppose from the current selected row)
For example
public int GetStudentID()
{
// The Student ID is the first cell of the current row
int Row = dataGridView1.CurrentRow.Index;
return Convert.ToInt32(dataGridView1[0,Row].Value);
}
public string GetISBN()
{
// The ISBN is the second cell of the current row
int Row = dataGridView1.CurrentRow.Index;
return dataGridView1[1,Row].Value.ToString();
}
In my example above I have used the AddWithValue method to add the parameters and their values to the command object. This method is handy because you could do everything with one line of code, but be aware that AddWithValue decides the datatype of the parameter by looking at the datatype of the value passed in. If your database field and your parameter don't match you could get errors or incorrect conversions. Also AddWithValue is less performant than an explicit declaration of the parameter and its datatype. Look at this very detailed article for a deeper understanding of parameter passing

Categories