SqlCommand string to RowdataBound Header - c#

I have created a method with a string "test" that holds my SqlCommand query.
test = '201813'
public void temp()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4)+ CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2))", con);
con.Open();
string test = (string)cmd.ExecuteScalar();
con.Close();
}
}
The question now is How can I reuse this string in my following rowdatabound event?
protected void gwPlanning_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > 0)
{
//Translate header text
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[12].Text = test.ToString();
}
}
}
I'm trying to use e.Row.Cells[12].Text = **test.ToString();
Can anyone help me on what im doing wrong?

In your code, the string variable test is a local variable for the temp() and if you want to use that it in gwPlanning_RowDataBound, either you have to make the function temp to return a string value or you have to save the value in a global variable.
temp() to return a string value.
Code:
public string temp()
{
string test = string.Empty;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4)
+ CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2))", con);
con.Open();
test = (string)cmd.ExecuteScalar();
con.Close();
}
return test;
}
protected void gwPlanning_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells.Count > 0)
{
//Translate header text
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[12].Text = temp().ToString();
}
}
}

Related

Why I can't change a single row?

When I sort the data according to the value named "TC NO" and make the edits, all the data in the table changes. For example; I have a, b, and c values. I'm trying to make the value "a" to "d" but the values a,b, and c each convert to the value "d". I just want the value I selected to change. Where am I doing wrong?
public partial class muster_guncelleme : Form
{
public muster_guncelleme()
{
InitializeComponent();
}
static string conString = "Server=localhost;Database=master; Trusted_Connection=True;";
SqlConnection baglanti = new SqlConnection(conString);
private void btn_arama_Click(object sender, EventArgs e)
{
baglanti.Open();
string kayit = "SELECT * from [user] where tc_no=#tc_no";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#tc_no", txt_tc.Text);
SqlDataAdapter da = new SqlDataAdapter(komut);
SqlDataReader dr = komut.ExecuteReader();
if (dr.Read())
{
lbl_tc.Text = dr["tc_no"].ToString();
txt_user.Text = dr["user_name"].ToString();
txt_pass.Text = dr["password"].ToString();
txt_name.Text = dr["full_name"].ToString();
bday_date.Text = dr["birth_date"].ToString();
txt_phone.Text = dr["phone_number"].ToString();
}
else
MessageBox.Show("Müşteri Bulunamadı.");
baglanti.Close();
}
private void muster_guncelleme_Load(object sender, EventArgs e)
{
}
private void btn_kaydet_Click(object sender, EventArgs e)
{
baglanti.Open();
string kayit = "update [user] set user_name=#user_name, password=#password, full_name=#full_name, phone_number=#phone_number";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#user_name", txt_user.Text);
komut.Parameters.AddWithValue("#password", txt_pass.Text);
komut.Parameters.AddWithValue("#full_name", txt_name.Text);
komut.Parameters.AddWithValue("#phone_number", txt_phone.Text);
komut.ExecuteNonQuery();
baglanti.Close();
MessageBox.Show("Kullanıcı Bilgileri Güncellendi.");
}
}

Insert from DataGridView to SQL Server

I'm trying to insert data to a SQL Server with a dataGridView.
Here's what I have now in my buttonSave_Click :
string conString = "xxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
SqlCommand insert = new SqlCommand("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
}
insert.ExecuteNonQuery();
insert.Parameters.Clear();
}
For now this piece of code has a weird behavior because it throws an exception System.Data.SqlClient.SqlException : Must declare the scalar variable "#size" but what I wrote in the cells is still added to the database.
very likely command cannot be executed on last DataGridView row, which is reserved for new item input. and all previous items are inserted properly.
it happens because (row.Cells[0].Value != null && row.Cells[1].Value != null) check for that row returns false and parameters are not added. the next statement insert.ExecuteNonQuery(); tries to run a command without required parameters and fails
create and execute insert command only for valid rows:
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
SqlCommand insert = new SqlCommand("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
insert.ExecuteNonQuery();
}
}
string conString = "xxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
foreach (DataGridViewRow row in dataGridViewStock.Rows)
{
SqlCommand insert = new SqlCommand();
if (row.Cells[0].Value != null && row.Cells[1].Value != null)
{
insert.Parameters.AddWithValue("#size", row.Cells[0].Value);
insert.Parameters.AddWithValue("#quantity", row.Cells[1].Value);
insert.Parameters.AddWithValue("#codeArticleComponent", labelComponentChosen.Text);
}
insert = ("INSERT INTO stock_test(size,quantity,codeArticleComponent) VALUES (#size,#quantity,#codeArticleComponent)", con);
insert.ExecuteNonQuery();
insert.Parameters.Clear();
}
The Error is occur as you are using the variable before declaring them. Please Declare them prior with value before using into the Query.
This should do what you want.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Stores";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
}
You can find LOTS of great examples from the link below.
http://csharp.net-informations.com/datagridview/csharp-datagridview-database-operations.htm

Update SQL query, unsure why it isn't working as no errors are appearing

I have been staring at this UPDATE statement for a long while and are unsure why my table isn't changing. When I press the button no error appears but my table doesn't not get updated either, I have checked that all of my variables have values on debug and they do.
I'd appreciate any help anyone can give me!
This is the code that contains the statement I need help with:
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
This is the whole code for my form if anyone wanted to look at it just in case that is affecting the button even handler:
namespace ComputingA2_Official_Project
{
public partial class CurrentlySetTestForm : Form
{
Timer loopTimer = new Timer();
private int CurrentQuestionID { get; set; }
private string QuestionSpace { get; set; }
public CurrentlySetTestForm()
{
InitializeComponent();
}
private void CurrentlySetTestForm_Load(object sender, EventArgs e)
{
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command18 = new SqlCommand("SELECT MIN([QuestionID]) AS QuestionID FROM QuestionStudentAssociation WHERE ( [StudentID]=#Signedinstudent AND [StudentAnswer] IS NULL )", connect);
command18.Parameters.AddWithValue("#Signedinstudent", y);
var reader = command18.ExecuteReader();
while (reader.Read())
{
CurrentQuestionID = Convert.ToInt32(reader[0]);
SqlCommand command19 = new SqlCommand("SELECT ([Question Space]) FROM Questions WHERE ([QuestionID]=#CurrentQID)", connect);
command19.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
using (SqlDataReader reader2 = command19.ExecuteReader())
{
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2[0]);
label1.Text = QuestionSpace;
}
}
}
connect.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
I believe the issue is that you are executing the command asynchronously (BeginExecuteNonQuery), but never calling EndExecuteNonQuery to commit it. I also suspect you could just call it synchronously like this:
command20.ExecuteNonQuery();

Filtering combobox with another combobox value

I have three combo-box which filtering value in different tables. For the first two combo-box i have no problem but for the third combo-box, I got error show input strings was not in correct format. I using the same code for the other two and it working correctly. Can someone specify how to troubleshoot this problem?
Here my code:-
This one is for combobox two which worked perfectly:-
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
This is the code which show error
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedValue.ToString() != null)
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
I hope someone can show me how to rectify this problem. Thanks.
***UPDATE****
Here the full code
private void FillPier(int BridgeID)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, PierName, BridgeID FROM tbPier WHERE BridgeID = #BridgeID";
cmd.Parameters.AddWithValue("#BridgeID", BridgeID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbPier.DataSource = objDs.Tables[0];
cbPier.DisplayMember = "PierName";
cbPier.ValueMember = "PierID";
}
}
private void FillDataPoint(int PierDP)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT PierID, InspectDate FROM tbDatapoint WHERE PierID = #PierID";
cmd.Parameters.AddWithValue("#PierID", PierDP);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
cbInspect.DataSource = objDs.Tables[0];
cbInspect.DisplayMember = "InspectDate";
cbInspect.ValueMember = "PierID";
}
}
private void ViewBridge_Load(object sender, EventArgs e)
{
FillBridge();
}
private void cbBridge_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbBridge.SelectedValue.ToString() != null)
{
int BridgeID = Convert.ToInt32(cbBridge.SelectedValue.ToString());
FillPier(BridgeID);
}
}
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbPier.SelectedIndex != 1)
{
int PierDP = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierDP);
}
}
Check if this can be converted to int first like this:
int x = 0
private void cbPier_SelectedIndexChanged(object sender, EventArgs e)
{
if (Int32.TryParse(cbPier.SelectedValue.ToString(), out x))
{
int PierID = Convert.ToInt32(cbPier.SelectedValue.ToString());
FillDataPoint(PierID);
}
}
Or using the SelectedIndex property:
if(cbPier.SelectedIndex != -1)
{
.....
}
What are the cbPier.DisplayMember and cbPier.ValueMember ? Is the diplay member the string and value member the int? Double check if that's the case first ...

Search and reload datagridview

I have a existing datagridview and a search textbox.
When I type a search text and click on the search button based on the below method (using stored procedures), I like to have it auto reload the datagridview with the search results.
How can I achieve this?
public static void searchAny(String searchFields, String tblName, String connectionString, SqlCommand tblscmd, SqlDataAdapter tbldataadaptor, DataTable tbldatatable, SqlCommandBuilder cmbuilder, DataGridView DataGridViewName)
{
using (SqlConnection tblconn = new SqlConnection(connectionString))
{
tblconn.Open();
SqlCommand tblcmd = new SqlCommand();
tblcmd.Connection = tblconn;
tblcmd.CommandType = CommandType.StoredProcedure;
tblcmd.CommandText = "usp_searchany";
tblcmd.Parameters.Add("#stringToFind", SqlDbType.NVarChar);
tblcmd.Parameters["#stringToFind"].Value = "%" + searchFields + "%";
tblcmd.Parameters.Add("#table", SqlDbType.NVarChar);
tblcmd.Parameters["#table"].Value = tblName;
cmbuilder.DataAdapter = tbldataadaptor;
tbldatatable.DefaultView.AllowDelete = true;
tbldatatable.DefaultView.AllowEdit = true;
tbldataadaptor.Fill(tbldatatable);
DataGridViewName.ReadOnly = false;
DataGridViewName.DataSource = tbldatatable;
tblconn.Close();
}
}
private void SearchButton_Click(object sender, EventArgs e)
{
tbldatatable.Clear();
String searchFields = SearchTextBox.Text;
GeneralMethods.searchAny(searchFields, "tblClients", connectionString, tblcmd, tbldataadaptor, tbldatatable, cmbuilder, dataGridView);
dataGridView.DataSource = tbldatatable;
dataGridView.Refresh();
}
You have to filter your DataGridView's DataSource...like the following way...It's not required to clear,bind or refresh the datagridview...
From the CellEndEidt this is possible....
Simply you can filter the DataGridView's DataSource
private void MyDataGrid1_CellEndEdit(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
if (e.RowIndex == 0)
{
if (myDataGrid1.CurrentCell.Value.ToString().Trim().Length > 0)
{
MyFilterString="Field1=Feild2 and Field3>Field4";
}
MyDtb1.DefaultView.RowFilter = FilterString;
}
}

Categories