I used datagrid to show sql table datagrid.
And I showed one column on datagrid from sql.
Now I want to determine that which rows is now open & what is that values.
Like this.
See what I want to do.
And I used this code to show datatable on my datagrid.
string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("cmt_7th");
sda.Fill(dt);
MydataGrid_roll.ItemsSource = dt.DefaultView;
}
And its show only row column. But I want to declare like my previous image.
You can get the selected row value with this code:
string em = dataGridView1.CurrentRow.Cells[2].FormattedValue.ToString();
You store the value in a string called em like the above, you can change the name for sure, and then cell[] is like an array, it stores each intersection of a row and a column in there, so for instance if you have 3 columns and two rows, the first intersection of the row and column is of index 0 and so on and so forth.
You could select all values that you are interested in up front of but only display the "roll" column in the DataGrid:
string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{
SqlCommand cmd = new SqlCommand("SELECT roll, tc, tf, pc, pf FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("cmt_7th");
sda.Fill(dt);
MydataGrid_roll.AutoGenerateColumns = false;
MydataGrid_roll.Columns.Add(new DataGridTextColumn() { Header = "roll", Binding = new Binding("roll") });
MydataGrid_roll.ItemsSource = dt.DefaultView;
}
You can then retrive any column values of the selected row in the DataGrid like this:
DataRowView drv = MydataGrid_roll.SelectedItem as DataRowView;
if(drv != null)
{
int selectedRoll = Convert.ToInt32(drv["roll"]);
if(drv["tc"] != DBNull.Value)
{
string selectedTc = drv["tc"].ToString();
}
//...
}
Related
So I have a dropdown list that is being populate from database, the goal is to get the selected values from the dropdown list and put in the gridview. The problem is it only adds one row and only updates that row when I try to select new values from the dropdownlist.
I have tried doing Datarow row = dt.newrow() but not luck
Back End code of button click
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Product_Details WHERE Model = '" + ddlModel.SelectedItem.Text + "' AND Price = '" +ddlPrice.SelectedItem.Text + "'", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
First image when I select values from dropdown list for first time
Second image is when I select new values from dropdown list but it updates previous table and does not add new row in gridview
On Add Button click you are retrieving new data from database and creating new datatable that's why you are loosing the previously selected data.
You need to maintain the previously retrieved data between two clicks on Add button.
You need to create a separate DataTable in aspx.cs and store it in the ViewState and add new row to that table on button click and re-bind it to the GridView.
You need to write following code to achieve this.
//This method will check if the table exist in the ViewState
//If table does not exist in ViewState, a new table will be created and stored in ViewState
private DataTable GetDataTable()
{
DataTable dt = ViewState["SelectedModels"] as DataTable;
if (dt == null)
{
dt = new DataTable();
dt.TableName = "ColorData";
dt.Columns.Add(new DataColumn("Model", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(string)));
ViewState["SelectedModels"] = dt;
}
return dt;
}
//This method will store DataTable to ViewState
private void SaveDataTable(DataTable dataTable)
{
ViewState["SelectedModels"] = dataTable;
}
//This method will get the data from the database, add it to the DataTable
//And it will re-bind the DataTable to the GridView and store the updated DataTable to ViewState
private void AddItemToList(string modelName, string price)
{
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd =
new SqlCommand("SELECT * FROM Product_Details WHERE Model = #modelName AND Price = #price", con))
{
var modelParameter = new SqlParameter();
modelParameter.ParameterName = "#modelName";
modelParameter.Value = modelName;
cmd.Parameters.Add(modelParameter);
var priceParameter = new SqlParameter();
priceParameter.ParameterName = "#price";
priceParameter.Value = price;
cmd.Parameters.Add(priceParameter);
con.Open();
using (var sqlReader = cmd.ExecuteReader())
{
var dataTable = GetDataTable();
while (sqlReader.Read())
{
var dataRow = dataTable.NewRow();
//Hear I assume that Product_Details table has Model and Price columns
//So that sqlReader["Model"] and sqlReader["Price"] will not have any issue.
dataRow["Model"] = sqlReader["Model"];
dataRow["Price"] = sqlReader["Price"];
dataTable.Rows.Add(dataRow);
}
SaveDataTable(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}
}
}
And now the Click Event Handler of the button should call the above method as following.
protected void bttnAdd_Click(object sender, EventArgs e)
{
AddItemToList(ddlModel.SelectedItem.Text, ddlPrice.SelectedItem.Text);
}
This should help you resolve your issue.
My Form consist of a DataGridView and, inside of that, I have one Column as ComboBox.
The ComboBox is getting filled by the database query.
I wanted to display the default value of ComboBox in the DataGridView. I have loaded values in combo box but could not find a way to set a default value for that.
I have added values to a combo box with the following code on the click of the btnLoadCombo button:
private void btnLoadCombo_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["InventoryManagerConnectionString"].ConnectionString);
//Filling ComboBoxes
con.Open();
SqlCommand cmdGetRootCat = new SqlCommand("SELECT * FROM tblProductCategories", con);
SqlDataReader sdaRootCat = cmdGetRootCat.ExecuteReader();
comboBoxCatTest.Items.Clear();
while (sdaRootCat.Read())
{
this.CatCombo.Items.Add(sdaRootCat["Cat_Name"]);
}
//Filling DataGridView
DataTable dt = new DataTable();
dt.Clear();
SqlCommand cmd = new SqlCommand("SELECT Cat_ID, Cat_Name FROM tblProductCategories", con);
SqlDataReader sda = cmd.ExecuteReader();
dt.Load(sda);
dataGridCatList.DataSource = dt;
con.Close();
}
I expect results as shown in image 2.
You can use
foreach(DataGridViewRow row in dataGridCatList.Rows)
{
if(row.Cells[3].Value != null) //ignore last row which is empty
{
if( row.Cells[3].Value.Equals(1018) )
row.Cells[0].Value = this.CatCombo.Items[0];
}
//...and so on
}
You are going through every row with the foreach() loop and compare the value of Cat_ParentCat with row.Cells[3].Value.Equals(Cat_ParentCatValue). If a match is found, set the default value of the ComboBox with row.Cells[0].Value = this.CatCombo.Items[yourDefaultValue];
i wonder, if there a way to capture data from multi rows from table, and copy that rows to another table.example table cart, i want capture their value from Cartid column and copy to
order table
...
SqlConnection conn = new SqlConnection(ConfigurationManager.
ConnectionStrings["connectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#email", Session["email"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
int count = int.Parse(Session["cartrows"].ToString());
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
Object objcartid = dt.Rows[0]["cartid"];
}
this what i do to capture Cartid from cart table.
i loss here.
You can use DataTable.Clone
But if you want only specific columns then you can try something like below (Considering order DataTable will be empty at first)
for(var i = 0; i < cart.Rows.Length; i++)
{
var cartId = cart.Rows[i]["cartid"]
DataRow row = order.NewRow();
row["cartid"] = cartId;
order.Rows.Add(row);
}
I am working with a simple application with c#
What I wan't to do is that when I retrieve data from SQL Database into Datagrid, i want some of rows to deleting by selecting them and then clicking a button.
The code i used to retrieve data is shown below:
SqlConnection conn = new SqlConnection("Server=MEO-PC;Database= autoser; Integrated Security = true");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From evidenc", conn);
DataTable dt = new DataTable("dtList");
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dtg.ItemsSource = dt.DefaultView;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
conn.Close();
Also the code i tried for deleting the specific row is:
if (dtg.SelectedIndex >= 0)
{
dtg.Items.RemoveAt(dtg.SelectedIndex);
}
The erro i get is :Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.
I don't know where is the problem cause I'am new to programming. Thanks to everyone
You need to remove the row from the DataTable. Try this:
DataRowView drv = dtg.SelectedItem as DataRowView;
if(drv != null)
{
DataView dataView = dtg.ItemsSource as DataView;
dataView.Table.Rows.Remove(drv.Row);
}
You can't remove an item from the Items collection when you have set the ItemsSource property.
You can use IEditableCollectionView to do this. You can directly change the underlying collection, if it allows changes to be made, by using the methods and properties that IEditableCollectionView exposes, regardless of the collection's type.
IEditableCollectionView iecv = CollectionViewSource.GetDefaultView(theDataGrid.ItemsSource) as IEditableCollectionView;
while (theDataGrid.SelectedIndex >= 0)
{
int selectedIndex = theDataGrid.SelectedIndex;
DataGridRow dgr = theDataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex) as DataGridRow;
dgr.IsSelected = false;
if (iecv.IsEditingItem)
{
// Deleting during an edit!
iecv.CommitEdit();
iecv.RemoveAt(selectedIndex);
}
else
{
iecv.RemoveAt(selectedIndex);
}
}
I my class DBConnect, I have this function to populate a ComboBox to database based on input query:
public void POPULATE_COMBOBOX(string query, ComboBox myComboBox)
{
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable myDataTable = new DataTable();
adapter.Fill(myDataTable);
myComboBox.DataSource = myDataTable;
this.CloseConnection();
}
}
And here's how I use it
DBConnect.POPULATE_COMBOBOX("SELECT NAME FROM users", comboBox_Name);
I have 3 rows in column NAME, and I expect those 3 names will be displayed in my comboBox_Name. However instead, I got 3 lines of System.Data.DataRowView in my combobox. Any idea how to convert those DataRowView to string?
You have to tell combobox what column to display.
//Preparation
var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("Name1");
dt.Rows.Add("Name2");
//Setup data binding
myComboBox.DataSource = dt.DefaultView;
myComboBox.DisplayMember = "Name";
myComboBox.ValueMember = "Name";
Then SelectedItem gets the actual ComboBox item (in this case a DataRowView), whereas SelectedValue gets the value of the property you specified as the ValueMember of the ComboBox
Or another way how to populate your ComboBox is:
MySqlDataReader sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
myComboBox.Items.Add(sqlReader["Name"].ToString());
}
sqlReader.Close();