Can help me to make Auto Generate ID? - c#

I have form want to Auto Generate that ID from Primary Key
so that code like that
private void setidphoto()
{
DataTable dt = con.FillTable("SELECT IDPhoto FROM Produksi ORDER BY IDPhoto DESC");
if (dt.Rows.Count == 0)
{
txtIdPhoto.Text = "PH001";
}
else {
string temp = dt.Rows[0][0].ToString();
int IDplus= int.Parse(temp.Substring(2)) + 1;
string NewID = String.Format("PH{0:000}", IDPlus);
txtIdPhoto.Text = NewID;
}
}
The Error is con.FillTable cant compile or run it, can you help me

Try this
SqlConnection con = new SqlConnection("yourconnectionstringhere");
SqlCommand com = new SqlCommand("SELECT IDPhoto FROM Produksi ORDER BY IDPhoto DESC", con);
SqlDataAdapter adp = new SqlDataAdapter(com);
DataTable dt = new DataTable();
add.SelectCommand = com;
adp.Fill(dt);

Related

NullReferenceException when using SQL Queries WPF C#

I am doing a little project and I got stuck at a certain point (I am new to C# WPF). What I want to do is I have some data tables called item, issue_note & items_in_Issue_Note. I want to get all the issue note details into a datagrid & after selecting a row and click view button, I want to display the items in that issue note. I can get the data using
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
but when I am going to use
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
the code throws a NullReferenceException (I want to use the SQL query, because I want to search issue notes by no and date).
I will add my code for reference.
Thank you!
public PnlISNDetails_SK()
{
InitializeComponent();
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
datagrid = dgISNDetails;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
addIssueNoteLogic = new AddIssueNoteLogic();
if(cmbSearchBy.Text== "ISSUE NOTE NO")
{
addIssueNoteLogic.ViewISNFromISNNo(txtSearchBox.Text).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "CREATED DATE")
{
addIssueNoteLogic.ViewISNFromCreatedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "ISSUED DATE")
{
addIssueNoteLogic.ViewISNFromIssuedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
}
Class code for search issue notes:
public SqlDataAdapter ViewISNFromISNNo(string searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issue_No like '%" + searchText + "%'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromCreatedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where created_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromIssuedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issued_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNDetails(string isnNo)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select Item.ItemCode,Item.itemName,Item.Unit,Items_In_Issue_Note.Issued_Qty,Issue_Note.Issue_No from ((Item inner join Items_In_Issue_Note on Item.ItemCode= " +
"Items_In_Issue_Note.ItemCode) inner join Issue_Note on Issue_Note.Issue_No = Items_In_Issue_Note.Issue_No)where Issue_Note.Issue_No = '"+isnNo+"'; ";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
This is the code for displaying items in issue note:
public void LoadGrid()
{
dt = new DataTable();
string isnNo = (PnlISNDetails_SK.datagrid.SelectedItem as Issue_Note).Issue_No; //Exception is thrown in here
addIssueNoteLogic = new AddIssueNoteLogic();
addIssueNoteLogic.ViewISNDetails(isnNo).Fill(dt);
dgItemsInISN.ItemsSource = dt.DefaultView;
}
Debug and verify that the connection to the database in your datacontext is not null or closed. specifically this part
db.Database

How to choose a name of data from sql table from another DataGridView using ComboBox in C#?

I have three tables: Patient, Doctor, Diagnosis. In the Diagnosis form I have two ComboBoxes, and I need to be able to choose the names of doctor and patient through these ComboBoxes.
Code of the methods:
void populatecombo()
{
string sql = "select * from Patient";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr;
try
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("PatId", typeof(int));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
PatId.ValueMember = "PatId";
PatId.DataSource = dt;
conn.Close();
}
catch
{
}
}
void populatedoc()
{
string mysql = "select * from Doctor";
SqlCommand cmd = new SqlCommand(mysql, conn);
SqlDataReader rdr;
try
{
conn.Open();
DataTable dt = new DataTable();
dt.Columns.Add("DocId", typeof(int));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
DocId.ValueMember = "DocId";
DocId.DataSource = dt;
conn.Close();
}
catch
{
}
}
string patname;
string docname;
void fetchpatientname()
{
string mysql = "select * from Patient where PatId=" + PatId.SelectedValue.ToString() + "";
SqlCommand cmd = new SqlCommand(mysql, conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
patname = dr["PatName"].ToString();
PatientTb.Text = patname;
}
}
void fetchdoctorname()
{
string str = "select * from Doctor where DocId=" + DocId.SelectedValue.ToString() + "";
SqlCommand cmd = new SqlCommand(str, conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
docname = dr["DocName"].ToString();
DocName.Text = docname;
}
}
So populatedoc and populatecombo should get the names of doctor and patient, and fetch should help to choose them from ComboBox, but it doesn't seem to work with the error:
System.Data.SqlClient.SqlException: "Incorrect syntax near '='."
Picture of the form:
Based on my test, I could not get the error you provided based on your code.
You could try to use SqlCommand.Parameters.AddWithValue method to do it.
void fetchpatientname()
{
conn.Open();
string mysql = "select * from Patient where PatId=#PatId";
SqlCommand cmd = new SqlCommand(mysql, conn);
cmd.Parameters.AddWithValue("#PatId", cmbPat.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
patname = dr["PatName"].ToString();
txtPatName.Text = patname;
}
conn.Close();
}
void fetchdoctorname()
{
conn.Open();
string str = "select * from Doctor where DocId=#DocId";
SqlCommand cmd = new SqlCommand(str, conn);
cmd.Parameters.AddWithValue("#DocId", cmbDoc.SelectedValue);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
docname = dr["DocName"].ToString();
txtDocName.Text = docname;
}
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
fetchdoctorname();
fetchpatientname();
}
Result:

How to delete multiple rows in C# using a SQL query?

I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}

Loop inside loop for .Net C#

I want to retrieve all User_id's next after my entered User_id referencing each other from the table by Reference_id, the code below gives the exact result but it retrieves all User_id's from "2001 to 2005".
I want if i enter the "2002" as User_id from a textbox then it must retrieve from "2003 - 2005"
Table_xyz column User_id have value= 2001, 2002, 2003, 2004, 2005
Table_xyz column Reference_id have value= 2000, 2001, 2002, 2003, 2004
var gCmd = new SqlCommand(#"SELECT User_id FROM Table_xyz", nCon);
SqlDataAdapter Sda = new SqlDataAdapter(gCmd);
DataTable Dt = new DataTable();
Sda.Fill(Dt);
for (int i = 0; i < Dt.Rows.Count; i++)
{
string referenceid = Dt.Rows[i]["User_id"].ToString();
var gCmd1 = new SqlCommand(#"SELECT User_id FROM Table_xyz
WHERE Reference_id = '" + referenceid + "'", nCon);
SqlDataAdapter Sda1 = new SqlDataAdapter(gCmd1);
DataTable Dt1 = new DataTable();
Sda1.Fill(Dt1);
Response.Write(referenceid);
}
I tried adding "SELECT User_id FROM Table_xyz WHERE User_id = '2001'" to the first command but it returns only a single value where User_id matched "2001"
This is the easiest solution. But consider refactoring your code or thinking on another approach, this is not perfomatic. Also consider using parameters on you sql command.
string initialId = Dt.Rows[0]["ID"].ToString();
do
{
string dCmd = "SELECT ID FROM TableA WHERE Reference_ID = '" + initialId + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
initialId = dDt.Rows[i]["ID"];
Response.Write(dDt.Rows[i]["ID"]);
}
}
while(dDt.Rows.Count > 0)
You can try this solution, in first you can get all distinct Refrence_ID and based on that you can loop to get IDs
var gCon = ConfigurationManager.ConnectionStrings["myCon"].ConnectionString;
using (var nCon = new SqlConnection(gCon))
{
try
{
nCon.Open();
String cmd = "SELECT DISTINCT Refrence_ID FROM TableA";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(cmd, nCon);
DataTable Dt = new DataTable();
adapter.Fill(Dt);
for (int count = 0; count < Dt.Rows.Count(); count++)
{
string dCmd = "SELECT ID FROM TableA WHERE Reference_ID = '" + dt.Rows[count]["Refrence_ID"] + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
Response.Write(dDt.Rows[i]["Distributor_ID"]);
}
}
}
catch (Exception e)
{
Response.Write(e.ToString());
}
finally { nCon.Close(); }
}
Thanks to all of you my friends for the effort to help me but unfortunately that didn't solved the main issue.
After lot's of research for the same i got my answer at "Recursive command", so finally my code is below
string value = "2723022"; // <== any reference id from Reference_id column
String gCmd = "SELECT DISTINCT Reference_id FROM myTable WHERE User_id >'" + value + "'";
SqlDataAdapter Sda = new SqlDataAdapter();
Sda.SelectCommand = new SqlCommand(gCmd, nCon);
DataTable Dt = new DataTable();
Sda.Fill(Dt);
for (int count = 0; count < Dt.Rows.Count; count++)
{
string dCmd = "SELECT User_id FROM dEmo_aCcounts WHERE Reference_id = '" + Dt.Rows[count]["Reference_id"] + "'";
SqlDataAdapter dSda = new SqlDataAdapter();
dSda.SelectCommand = new SqlCommand(dCmd, nCon);
DataTable dDt = new DataTable();
dSda.Fill(dDt);
for (int i = 0; i < dDt.Rows.Count; i++)
{
Response.Write(dDt.Rows[i]["User_id"]);
}
}

datagridviewcombobox columns Dependent on another column

How To Do This Work on gridviewcomboboxcolumns any idea plx
//Form Load Event
string query="select article_name from article";
SqlCommmand cmd = new SqlCommand(query,con);
SqlDataAdapter da= new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
combobox1.items.clear();
for(int i=0;i<dt.rows.count;i++)
{
combobox1.items.add(dt.rows[i].cells[0].toString());
}
\ComboBox1 Selected IndexChange Event
string query1="select description from article where article_name='"+combobox1.selectedItem.ToString()+"'";
SqlCommmand cmd1 = new SqlCommand(query1,con);
SqlDataAdapter da1= new SqlDataAdapter(cmd);
DataTable dt1=new DataTable();
da1.Fill(dt1);
combobox2.items.clear();
for(int i=0;i<dt1.rows.count;i++)
{
combobox2.items.add(dt1.rows[i].cells[0].toString());
}
\Now Assume these 2 combox is gridviewCombobox Columns so how to make
this work on gridviewcombobox columns
Project in Windows Form in C#
I m posting this answer after a few months because its helps for
thoose whoose facing problem on DataGridviewComboboxcell
I did my own skill First Fill my first/Main Column
SqlCommand objCmd = new SqlCommand("select distinct article_name from Setup_article_custominvoice", con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
article.DataSource = dt;
//this column1 will display as text
article.DisplayMember = "article_name";
After that i was going on Cell End Edit
if (dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells["article_name"])
{
string CategoryValue = "";
//string CategoryValue1 = "";
if (dataGridView1.CurrentCell.Value != null)
{
CategoryValue = dataGridView1.CurrentCell.Value.ToString();
//CategoryValue1 = dataGridView1.CurrentCell.Value.ToString();
}
//SqlConnection objCon = new SqlConnection(#"Data Source=.\SqlExpress;Initial Catalog=dbTest3;Integrated Security=True");
string query = "select article_name,composition from Setup_article_custominvoice where article_name='" + CategoryValue + "'";
SqlCommand objCmd = new SqlCommand(query, con);
SqlDataAdapter objDA = new SqlDataAdapter(objCmd);
objDA.SelectCommand.CommandText = objCmd.CommandText.ToString();
DataTable dt = new DataTable();
objDA.Fill(dt);
DataGridViewComboBoxCell t = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2] as DataGridViewComboBoxCell;
t.DataSource = dt;
t.DisplayMember = "composition";
}

Categories