Issue Populating the details view grid with selectedindex gridview - ASP.NET , C# - c#

On My ASP.NET page i have a dropdown list - which contains all the table names from the DB. On selecting one table from the list, a gridview below is populated with the information found in that table.
Some of the tables have plenty of columns and making it impossible to view, So l included a details view to help me to view all the columns.
On selecting a row in the gridview, the details view is populated by the rows data. AS each table has different column names and numbers, i am facing problem that the DetailsView is not populated by anything and when l click 'Edit' or 'Delete'. It gives an error that the events were not handled.
Any pointers/help would be appreciated. As should be able ot edit the information, then update it in the gridview and in turn updating it in the table.
Here is my code for populating the DetailsView
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
dtvInformation.DataSource = GridView1.SelectedRow.ToString();
dtvInformation.DataBind();
}
Below is my code for populating the Gridview
protected void DropDownList1_SelectedIndexChanged (object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter(string.Format ("SELECT * FROM {0}", drpTable.SelectedValue), con);
DataSet ds = new DataSet ();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}

Related

How to make a column read only in data grid in asp.net

I have created a DataGrid and I take the data from database and put it in there.All the data retrieval are done by dynamically in the code behind.Here is a some portion of my code.
SqlConnection con = new SqlConnection("Data Source=PUNUTHL\\SQL;Initial Catalog=mytest;Integrated Security=True");
SqlDataAdapter ad;
DataSet ds = new DataSet();
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ad = new SqlDataAdapter("Select * from product",con);
ad.Fill(ds);
dt = ds.Tables[0];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
Upto this point it works perfectly.
But I wanted to add the edit function for that DataGrid
But according to my query I took the "product_ID" values as well which can not allows to be updated.
Since I use both "Etid" and "Delete" commands, "prodcut-id" may be my 3rd column as shown in the picture.
So I wanted to be that column read only when the client hit on the edit button.So how can I tackle this problem.Are there any way to get the column names or column indexed?Please can some one help me.
This is one of the way to make a column at any index readonly.
DT.Columns(0).ReadOnly = True '// Make the column(0) readonly and assign to DataGrid.
Datagrid!.DataSource = DT
where DT is datatable used to collect the data from database and is datasource to the datagrid Datagrid1.
For further editing make the column readonly= false and make changes and again turn it into readonly.
Here in your case you can make your Id column that is 2 as readonly

How to show a specific item in dropdownlist based on specific value of a cell of a table-row in asp.net gridview control?

i am new to asp.net. I am building an admin page and i want to display employee's data in GridView by fetching it from database table. Table has 3 columns (id, name, isManager). There are three possible values for "isManager" column. These values are "yes", "no" and "null". The admin has right to decide for an employee to make him a manager by selecting "yes" or "no" from DropDownList.
This admin page has a GridView control that contains two BoundFileds (i.e. id & name) and one template field (i.e. DropDownList). I am having difficulty in displaying "isManager" column values in DropDownList. I want DropDownList to display selected value/text as "yes" if database table-row has "yes" in "isManager" column, "no" if there is "no" in table-row and display an item "Select Choice" if table-row contains a null value.
My code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select * from tblUsersTable";
DataSet ds = DataBaseConnectivity.GetData(query);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
// RowDataBound() method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
DataSet ds = DataBaseConnectivity.GetData
("select distinct [isManager] from tblUsersTable");
ddlManager.DataSource = ds;
ddlManager.DataTextField = "isManager";
ddlManager.DataValueField = "isManager";
ddlManager.DataBind();
ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
/* After these lines of code i am not finding the right way to implement my logic
*/
Help me to figure it out.
You have to use the DataItem of the GridViewRow to access the underyling record. Then you can select the corect item via DropDownList.SelectedValue:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
DataSet ds = DataBaseConnectivity.GetData
("select distinct [isManager] from tblUsersTable");
ddlManager.DataSource = ds;
ddlManager.DataTextField = "isManager";
ddlManager.DataValueField = "isManager";
ddlManager.DataBind();
ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
DataRow row = ((DataRowView)e.Row.DataItem).Row;
bool isManager= row.Field<bool>("isManager"); // use the correct type if it's not bool
ddlManager.SelectedValue = isManager.ToString();
Apart from that, i would not use such db-helper classes like DataBaseConnectivity in ASP.NET. They are just a source for nasty errors or performance issues, all the more if you use a static connection. Further informations here.

Refresh one row in Dataset from Database before show edit form

I have a DataSet + TableAdapter and bound dataGridView. I have an edit button which opens a new form with details to edit (WinForms). How do I refresh one row (selected one) in the Dataset and in dataGrid from database before opening the new form?
Example: Two users A and B. User A changed record ID(10) and user B still has the old value in record ID(10). User B presses edit button and should get fresh data from database (data after change made by user A).
string sql = "SELECT * FROM Orders";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
da.Fill(ds, "Orders");
connection.Close();
dataGridView1.DataSource = ds;
.....
private void button1_Click(object sender, EventArgs e)
{
//?
//refresh selected row in datagrid (from current database record)
//?
EditForm()
}
Create a new query in your TableAdapter that should only get one row and call it with just the primary key of the row you already have.
Plug the result into a new DataSet and grab the first row (after checking for Rows.Count() > 0)
I would enclose the populating the gridview bit in it's own method say something like fill_grid(). Then just call the method in the edit link click event. Then whatever has changed will update. Then add the method to all the other button link events too. Then every time the user is clicking a link the grid "refreshes" essentially.
For those who is looking for the answer in 2019,
assuming dataAdapter is a defined earlier class member
private void ButtonUpdate_Click(object sender, RoutedEventArgs e)
{
if (dataGrid.SelectedItem is DataRowView view)
{
DataRow currentRow = view.Row;
DataTable table = currentRow.Table;
dataAdapter.Fill(table.Rows.IndexOf(currentRow), 1, table);
}
}

Refresh button - Refreshing data grid view after inserting, deleting, updating

I'm trying to create a refresh button to automatically refresh the data inside my datagridview after i have finish updating them.
However, my refresh button doesn't seem to work. The data displayed remains the same as the original one. It only gets updated after i manually end my windows app and rebuild it.
Here is my code:
private void button_refresh_Click(object sender, EventArgs e)
{
this.acuzioSecureStore_DatabaseXDataSet.AcceptChanges();
}
Please assist. thanks ^_^
The easiest way to handle this is to use a Binding Source object.
If your loading information into your DataGridView from an Access Database then your most likely storing the Data in a Dataset or DataTable.
Create a Binding Source object, and once you have populated your DataTable/Dataset, set the datasource for your Binding Source to your DataTable. Then set the Datasource from the DataGridView as the Binding Source object.
Doing this ensures that any changes in your datagridview or reflected in the DataTable and vice Versa. If you reload data into your DataTable it will reflect in the Data Grid Automatically.
DataTable dt = new DataTable();
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource= bs;
All changes will now happen automatically.
Hey the solution above is good but when the above code is executed,the table disappears and is not seen. And if I execute
da.Fill(ds, "p");
dataGridView1.DataSource = ds.Tables["p"];
then whole table is created again.
private void button_refresh_Click(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection(#"");
string query="select * from abc";
SqlCommand cmd=new SqlCommand(query,con);
SqlDataAdapter da=new SqlDataadapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
I had a datagridview, bound to a table in an Entity Framework database:
dataGridView1.DataSource = MyDatabase.MyTable;
It would never refresh despite two wasted days.
I solved it with a simple workaround:
private void button_refresh_Click(object sender, EventArgs e) {
dataGridView1.DataSource = MyDatabase.MyTable.Where(i =>(true));
}
This is an ugly workaround, and friend explained me how it works - if I do just dataGridView1.DataSource = database.table, it will cache the table and use the cached data forever. The fact that each time we create a new dummy query, prevents .net from caching it.
Please try this, it worked for me and let me know if you have any better option.
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.Refresh();
}
you Can Bind dataGridView On PageLoad or UserControl Load Event and After chage in grid view Call the Load Event
like
this.ucUsers_Load(null, null); // Windows From C#

Variable Scope issue in C#

Here is the deal. I have a Master-Detail Grid scenario. The Master GridView is loaded when the page is loaded. I am using a DataView of same DataTable which loads the Master to load the Detail GridView, by filtering what I need to show in the DetailGridView. Everything works fine when I view the first row of the MasterGridView. When I try to view the second row, I the the error "column[number] not found. I also notice that the "table" variable is nothing.
public partial class Gridview_Template : System.Web.UI.Page
{
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
SqlDataReader reader = DBSqlHelperFactory.ExecuteReader(
myconnection,
"crm_getcustomersummary",
new SqlParameter("#customerid", "99999")
);
table.Load(reader);
MasterGridView.DataSource = table;
MasterGridView.DataBind();
}
protected void detailGrid_DataSelect(object sender, EventArgs e)
{
string searchValue ="number=" + values.ToString();
DataView dv = new DataView(
table, searchValue, "number", DataViewRowState.OriginalRows
);
DetailGridView.DataSource = dv;
// ...
}
}
Am I to put the "table" variable in a session state so it exists across call?
If you just want to persist the table between postback, then you may want to take a look at ViewState. Session is used more for persisting information across different pages.

Categories