How to generate linkage checkbox (C #)? - checkbox

initial we will see two checkbox
No.1: Fruit
No.2: Animals
if select checkbox1 then display
□ Bananas
□ Apple
if select checkbox2 then display
□ Dog
□ Cat
□ Monkeys
I do not know how to write it with asp.net(c#), (they begin with SQL binding lists), thank you very much !!!
the initial two checkbox is use
Front End:
<asp:CheckBoxList ID="chkFruit_animal" runat="server"
onload="CheckBoxFruit_animal_Load" >
</asp:CheckBoxList>
Code Behined:
protected void CheckBoxFruit_animal_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string sqlstr;
sqlstr = "SELECT DISTINCT * From fa";
MySqlDataAdapter myAdapter = new MySqlDataAdapter();
MySqlConnection dbconn = new MySqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
DataSet ds = new DataSet();
myAdapter.SelectCommand = new MySqlCommand(sqlstr, dbconn);
myAdapter.Fill(ds, "fa");
chkFruit_animal.DataSource = ds.Tables["fa"];
chkFruit_animal.DataTextField = "faName";
chkFruit_animal.DataValueField = "faID";
chkFruit_animal.DataBind();
}
}
Database:
[fa]
faID|faname
1 |Fruit
2 |Animals
[teamName]
faID|Tname
1 |Bananas
1 |Apple
2 |Dog
2 |Cat
2 |Monkeys

Update code
Front End:
<div>
<div>
<asp:CheckBoxList ID="chkFruit_Animal" runat="server" OnCheckedChanged="chkFruit_Animal_CheckedChanged" ></asp:CheckBoxList>
</div>
<asp:CheckBoxList ID="chkBind" runat="server"></asp:CheckBoxList>
</div>
Code Behined
protected void Page_Load(object sender, EventArgs e)
{
//Console.WriteLine(json);
if (!IsPostBack)
{
//get the data from database
DataTable dtFruitAnimal = new DataTable("Name");
dtFruitAnimal.Columns.Add("faID");
dtFruitAnimal.Columns.Add("faname");
dtFruitAnimal.Rows.Add("1","Fruit");
dtFruitAnimal.Rows.Add("2","Animals");
chkFruit_Animal.DataSource = dtFruitAnimal;
chkFruit_Animal.DataTextField = "faID";
chkFruit_Animal.DataValueField = "faname";
chkFruit_Animal.DataBind();
}
}
protected void chkFruit_Animal_CheckedChanged(object sender, EventArgs e)
{
string value = chkFruit_Animal.SelectedValue;
DataTable dtResult = GetData(value);
chkBind.DataSource = dtResult;
chkBind.DataTextField = "faID";
chkBind.DataValueField = "Tname";
chkBind.DataBind();
}
public DataTable GetData(string strValue)
{
DataTable dt = new DataTable("DtResult");
string sqlQuery = "SELECT DISTINCT * From teamName where faId=#value";
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con))
{
da.SelectCommand.CommandType = CommandType.Text;
da.SelectCommand.Parameters.AddWithValue("#value", strValue);
da.Fill(dt);
}
}
return dt;
}

Related

I need to bound from query row to a label.text

Please look at code below and help me with your experience. I need to pull out company name from query and bound it to the lblCustName.text I tried different method but still I am getting errors. Please help to fix this problem.
public partial class frmMTO : Form
{
static string constring = ConfigurationManager.ConnectionStrings["cfTrack.Properties.Settings.Setting"].ConnectionString;
DataTable mtotbl = new DataTable("tbl");
public frmMTO()
{
InitializeComponent();
}
private void frmMTO_Load(object sender, EventArgs e)
{
btnStart.Enabled = false;
lblCustName.Text = "";
// Binding data to Customers List
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT Quote_No, Company FROM tblRFQ_logs ORDER BY Quote_No DESC", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
cmRFQ.ValueMember = "id";
cmRFQ.DisplayMember = "Quote_No";
cmRFQ.DataSource = dt;
SqlDataAdapter materiaDA = new SqlDataAdapter("SELECT Grade FROM tblMaterialGrades", con);
DataTable materialDT = new System.Data.DataTable();
materiaDA.Fill(materialDT);
cmMaterial.ValueMember = "Grade_id";
cmMaterial.DisplayMember = "Grade";
cmMaterial.DataSource = materialDT;
// Closing Connection
con.Close();
mtotbl.Columns.Add("ID", typeof(int));
mtotbl.Columns.Add("Material", typeof(string));
mtotbl.Columns.Add("Item Mark", typeof(string));
mtotbl.Columns.Add("Short Code", typeof(string));
mtotbl.Columns.Add("Description", typeof(string));
mtotbl.Columns.Add("Unit", typeof(string));
mtotbl.Columns.Add("QTY.", typeof(string));
mtotbl.Rows.Add(1, "SA-106 B", "N1", "PIP4STD106","4in STD SA-106B, SMLS", "in.", "6");
dataGridView1.DataSource = mtotbl;
}
private void cmRFQ_SelectedValueChanged(object sender, EventArgs e)
{
// here I need to change the label text
lblCustName.Text = "Company" <------ this data comes from query
}
Thanks for your reply
Assuming that you bind the selected index change to this function.
cmRFQ.SelectedIndexChanged += new System.EventHandler(list_SelectedIndexChanged);
I think what you're looking for is this:
protected void list_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;
string value = (string)list.SelectedValue;
lblCustName.Text = value
}

C#: Windows Form creating table and and retrieve data from database by each dynamic button click

I am trying to develop a restaurant billing application in windows form.
so I created dynamic buttons.
now I need a table which will retrieve data from database for each button click.
How can it possible?
private void newb_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// textBox1.Text = btn.Text;
connection con = new connection();
con.connecting();
// Button b = new Button();
int i = 0;
var query = "select itemname,itemcode,price from item_master where itemcode =" + btn.Name;
MySqlCommand cmd = new MySqlCommand(query, con.con);
while (i < 10)
{
MySqlDataAdapter sda = new MySqlDataAdapter();
DataTable dt = new DataTable();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
// MessageBox.Show(btn.Name);
i++;
}
// sda.Update(dbdataset);
// =dataGridView1.Rows[0]
//// MySqlDataReader mdr;
//// mdr = cmd.ExecuteReader();
// while (mdr.Read())
// {
//// textBox1.Text = (mdr["itemname"].ToString());
// }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}

fill textbox on second combobox selection changed in cascading combobox in windows form using c#

I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.

Retrieve data in dropdown from SQL Server database

I have two tables, one is dept and the other is emp with primary and foreign key relationship from emp.deptid which is a foreign key to dept.id. I have an aspx webpage and I have a dropdown list on it which I want to use to select dname form dropdown. But when I try to execute this code I get an error
Fill: SelectCommand.Connection property has not been initialized.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{ }
binddeptdropdown();
}
void binddeptdropdown()
{
SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
DataSet ds = new DataSet();
da.Fill(ds, "dept");
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "dname";
DropDownList1.DataTextField = "deptid";
DropDownList1.DataBind();
}
Your closing brace on your using function is in the wrong place, and your connection object needs to be passed to your function.
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["practproject"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
binddeptdropdown(con );
}
}
void binddeptdropdown(SQLConnection con)
{
SqlDataAdapter da = new SqlDataAdapter("select * from dept", con);
DataSet ds = new DataSet();
da.Fill(ds, "dept");
DropDownList1.DataSource = ds;
DropDownList1.DataValueField = "dname";
DropDownList1.DataTextField = "deptid";
DropDownList1.DataBind();
}

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

my error is simple but for me it is hard to fix it because my knowledge is not good . which is when i Enter the record by clicking the Addbutton of AddStudent record then the record that i deleted like record StudentID = 1, FirstName =Raju ,LastName=Abbasi
After Delete it again and press save Change even After that when i again try to use the ID=1 means enter the Record with ID=1 that i have been deleted and record the StudentID=1 ,FirstName =Ram ,LastName=Rakish .Then error is occur which is
private static SqlDataAdapter CreateSutdentDataAdapter()
{
string gettSQL = "SELECT * FROM Student";
string insertSQL = "SET IDENTITY_INSERT Student ON;INSERT INTO Student(StudentID, FirstName,LastName,Gender,GPA,MyImage)" +
"VALUES (#StudentID,#FirstName,#LastName,#Gender,#GPA,#MyImage);SET IDENTITY_INSERT Student OFF";
string updateSQL = "UPDATE Student SET FirstName=#FirstName,LastName=#LastName ,Gender=#Gender, MyImage=#MyImage," +
" GPA=#GPA WHERE StudentID=#StudentID";
string deleteSQL = "DELETE FROM Student WHERE StudentID=#StudentID";
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = new SqlCommand(gettSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand = new SqlCommand(insertSQL, ConnectionManager.GetConnection());
dataAdapter.InsertCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.InsertCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.InsertCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.InsertCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.InsertCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.InsertCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.UpdateCommand = new SqlCommand(updateSQL, ConnectionManager.GetConnection());
dataAdapter.UpdateCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
dataAdapter.UpdateCommand.Parameters.Add("#FirstName", SqlDbType.VarChar,25 ).SourceColumn = "FirstName";
dataAdapter.UpdateCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 25 ).SourceColumn = "LastName";
dataAdapter.UpdateCommand.Parameters.Add("#Gender", SqlDbType.VarChar ,1).SourceColumn = "Gender";
dataAdapter.UpdateCommand.Parameters.Add("#GPA", SqlDbType.Float ).SourceColumn = "GPA";
dataAdapter.UpdateCommand.Parameters.Add("#MyImage", SqlDbType.VarBinary).SourceColumn = "MyImage";
dataAdapter.DeleteCommand = new SqlCommand(deleteSQL, ConnectionManager.GetConnection());
dataAdapter.DeleteCommand.Parameters.Add("#StudentID", SqlDbType.Int).SourceColumn = "StudentID";
return dataAdapter;
}
private static void DefinestudentTableSchema(DataTable table)
{
DataColumn StudentIDColumn = table.Columns.Add("StudentID", typeof(string));
StudentIDColumn.AllowDBNull = false;
table.PrimaryKey = new DataColumn[] { StudentIDColumn };
DataColumn StudentFirstName = table.Columns.Add("FirstName", typeof(string));
StudentFirstName.MaxLength = 150;
DataColumn StudentLastName = table.Columns.Add("LastName", typeof(string));
StudentLastName.MaxLength = 150;
DataColumn StudentGender = table.Columns.Add("Gender", typeof(string ));
DataColumn StudentGPA = table.Columns.Add("GPA", typeof(string ));
DataColumn StudentImage = table.Columns.Add("MyImage", typeof(Byte[]));
}
private static DataSet CreateStudentTrackerDataSet()
{
DataSet StudentTrackerDataSet = new DataSet();
DataTable StudentTable = StudentTrackerDataSet.Tables.Add("Student");
DefinestudentTableSchema(StudentTable);
return StudentTrackerDataSet;
}
public static DataSet GetData()
{
DataSet StudentTrakerDataSet = CreateStudentTrackerDataSet();
StudentTrakerDataSet.EnforceConstraints = false;
StudentDataAdapter.Fill(StudentTrakerDataSet.Tables["Student"]);
StudentTrakerDataSet.EnforceConstraints = true;
return StudentTrakerDataSet;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
public static void SaveData(ref DataSet changesDataSet)
{
DataSet addedDataSet = changesDataSet.GetChanges(DataRowState.Added);
if (addedDataSet != null)
{
StudentDataAdapter.Update(addedDataSet.Tables["Student"]);
changesDataSet.Merge(addedDataSet); // Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
}
DataSet modifiedDataSet = changesDataSet.GetChanges(DataRowState.Modified);
if (modifiedDataSet != null)
{
StudentDataAdapter.Update(modifiedDataSet.Tables["Student"]);
changesDataSet.Merge(modifiedDataSet);
}
DataSet deletedDataSet = changesDataSet.GetChanges(DataRowState.Deleted);
if (deletedDataSet != null)
{
StudentDataAdapter.Update(deletedDataSet.Tables["Student"]);
deletedDataSet.Merge(deletedDataSet);
}
here is my Addmodifyform logic for add the StudentID
public partial class AddModifyStudentRecords : Form
{
DataSet StudentTrackerDataSet;
DataRow currentRow;
public AddModifyStudentRecords()
{
InitializeComponent();
}
public AddModifyStudentRecords(DataSet ds)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = null;
}
public AddModifyStudentRecords(DataSet ds, DataRow row)
{
InitializeComponent();
StudentTrackerDataSet = ds;
currentRow = row;
textBox1.Text =currentRow["StudentID"] .ToString();
textBox2.Text = currentRow["FirstName"].ToString();
textBox4.Text = currentRow["LastName"].ToString();
textBox3.Text = currentRow["Gender"].ToString();
textBox5.Text = currentRow["GPA"].ToString();
txtBrowseFile.Text = currentRow["MyImage"].ToString ();
byte[] data = (byte[])currentRow ["MyImage"];
MemoryStream ms = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(ms);
string StudentID = textBox1.Text.ToString();
string StudentFirstName = textBox2.Text.ToString();
string StudentLastName = textBox4.Text.ToString();
string Gender = textBox3.Text.ToString();
string GPA = textBox5.Text.ToString();
Image MyImage = pictureBox1.Image;
DataTable table = StudentTrackerDataSet.Tables["Student"];
if (currentRow == null) {
currentRow = table.NewRow();
currentRow["StudentID"] = textBox1.Text.ToString();
table.Rows.Add(currentRow );
}
currentRow .BeginEdit();
currentRow ["StudentID" ]=StudentID ;
currentRow["FirstName"] = StudentFirstName;
currentRow["LastName"] = StudentLastName;
currentRow["Gender"] = Gender;
currentRow["GPA"] = GPA;
currentRow["MyImage"] = convertToByte(txtBrowseFile.Text);
currentRow.EndEdit();
Close();
}
public partial class AditStudent : Form
{
// Creat the Class variabl Dataset to track the Student
private DataSet StudentTrackerDataset;
public AditStudent()
{
InitializeComponent();
dataGridView1.DataError += DataGridView1_DataError;
StudentTrackerDataset = ProjectOfSchool.DataAccessLayer.DAC.GetData();
DataTable StudentTable = StudentTrackerDataset.Tables["Student"];
dataGridView1.DataSource = StudentTable;
//StudentTable.Columns["ID"].AutoIncrement = true;
for (int i = 0; i < dataGridView1.Columns.Count; i++)
if (dataGridView1.Columns[i] is DataGridViewImageColumn)
{
((DataGridViewImageColumn)dataGridView1.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}
}
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
string message = string.Format("Error in {0} columan in row {1}:{2}", e.ColumnIndex, e.RowIndex, e.Exception.Message);
MessageBox.Show(message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void button1_Click(object sender, EventArgs e)
{
AddModifyStudentRecords AddStudent = new AddModifyStudentRecords(StudentTrackerDataset);
AddStudent.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow StudentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
AddModifyStudentRecords modifyStudent = new AddModifyStudentRecords(StudentTrackerDataset, StudentRow);
modifyStudent.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure", "Delete Current Row", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
object id = dataGridView1.CurrentRow.Cells["StudentID"].Value;
DataRow currentRow = StudentTrackerDataset.Tables["Student"].Rows.Find(id);
currentRow.Delete();
}
}
private void button4_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Change to Save ", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
try
{
DataSet changesDateSet = StudentTrackerDataset.GetChanges();
ProjectOfSchool.DataAccessLayer.DAC.SaveData(ref changesDateSet);
StudentTrackerDataset.Merge(DAC.GetData());
MessageBox.Show("Data Save Successfully.", "Save Changes");
}
catch (SqlException ex)
{
MessageBox.Show("Data Not Saved:" + ex.Message, "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void button5_Click(object sender, EventArgs e)
{
if (!StudentTrackerDataset.HasChanges())
{
MessageBox.Show("There are no Changes to Save.", "Save Changes", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
DialogResult result = MessageBox .Show ("Are you Sure?","Reject Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes )
{
StudentTrackerDataset.RejectChanges();
}
}
}
And When i terminate the program and re execute the program then i saw that StudntID=1 is also save to Database with ID=1
or When i Delete the StudentID =1 and press save Change after press save Change when i also Terminate the program and re exicute the program and after that when i Enter the StudentID =1 Then no error is occur
And other way without termination is to Delete the record StudentID1 but when you Add the Student record but not Add the StudentID=1 But add the StudentID other then 1 in this case error is also not happend . Dear Sherik I have been solve my other error but i have still error which is in my Tittle So please responding me for this error And i re edited my code also So please replay me Thanks
I have record in my Database which have following Datatype as
StudentID=INT,
FirstName=VarChar,
LastName=VarChar,
Gender=Varchar,
GPA=Float,
MyImage=Vabinary (MAX)
Or may be Datarow fail to Delete the record or Update the record. I don't know please tell me and thanks to reply me and I am waiting for your reply.
The error message seems to indicate that you are hitting a Primary Key constraint.
I would suggest that you first stop allowing the user to enter the Student ID field. Let it be generated as an auto increment key in whatever database you are using. In Access, it is called AutoNumber.
Once you have done that, re test and post the results.

Resources