I've been struggling with displaying the resultset of a stored procedure in a grid view on the click of a button.
My issue is that am working on the existing code of a portal based on 3-tier architecture which doesn't allow me to use stuff like SqlDataAdapter and such. Because such functionality have already been incorporated by some methods which are available in the form of dlls.
I've tried returning a DataTable or a DataSet as the data source of the gridview but in vain.
Please help me by suggesting if there is any alternative object that can be assigned to the datasource of the gridview.. I am new to all this.. Any help is most appreciated !!
Here is my code:
DataAccess Layer:
public IDataReader BindGridView(string rgn)
{
string spdName = "spd_get_default_region";
DbCommand cmd = DB.GetStoredProcCommand(spdName);
DB.AddInParameter(cmd, "Rgn", DbType.String, rgn);
IDataReader idr = cmd.ExecuteReader();
return idr;
}
Here, GetStoredProcCommand is a built-in method. gvAll is the ID of the gridview.
Grid.aspx.cs:
protected void Go_Rgn_Click(object sender, EventArgs e)
{
DAL da=new DAL();
plhTable.Visible = true;
plhChoose.Visible = false;
plhForm.Visible = false;
string Rgn = afRgn.Text;
gvAll.DataSource = da.BindGridView(Rgn);
gvAll.DataBind();
}
A simple alternative is to create a dataTable object.
DataTable defaultRegion = new DataTable();
defaultRegion.Load(cmd.ExecuteReader());
gvAll.DataSource = table;
gvAll.DataBind();
Related
I am hitting a wall with populating a Gridview in ASP.NET CSHTML.
On Page Load, I have this code to initiate data fill.
protected void Page_Load(object sender, EventArgs e)
{
Orisoftds = new DataSet();
using (SqlConnection appCon = new SqlConnection(appdb))
{
SqlDataAdapter orisoftAdapter = new SqlDataAdapter(fillist, appCon);
orisoftAdapter.Fill(Orisoftds, "Staff_List");
}
GridView1.DataSource = Orisoftds.Tables["Staff_List"];
}
With this , the GridView1 will now have a DataSource
On my web page I have these three controls :
In this project , user will have to fill in their ID on the Text box and by clicking the submit button, the GridView will be filled in.
On the submit button, I have these code :
protected void EmpIDSubmit_Click(object sender, EventArgs e)
{
string eID = empIDTextBox.Text;
((DataTable)GridView1.DataSource).DefaultView.RowFilter = "EMPLOYEE_ID = " + eID;
}
Am I missing anything as at the moment when I enter an ID to the textbox, the page will instead just do thing or seems like it refreshed doing nothing.
Is there a difference between filling a Gridview in WinForms and HTML?
Result should contain gridview showing only the user's profile filtered based on their ID given.
You are Missing GridView1.Databind() for DataBind with Gridview,
Please use this line after:
GridView1.DataSource = Orisoftds.Tables["Staff_List"];
I believe you are missing the DataBind method. Try calling GridView1.Databind() in your EmpIDSubmit_Click event.
Answer - I am missing databind.
GridView1.DataBind();
I had a problem where even after databind , the result did not show.
Apparently the submit button has a broken PostBackUrl configuration as i was testing another method earlier.
I deleted my button and replaced with a new one , now results are showing properly.
I no longer need to use a stored procedure method such as :
using (SqlConnection appCon = new SqlConnection(appdb))
{
using (SqlCommand cmd = new SqlCommand("StoredProcedureName", appCon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EMPLOYEE_ID", empIDTextBox.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Thank you everyone.
I am using Telerik's Radgridview. I currently have it populated with data from a test database and I do this by using a linq query when the window loads. I have two extra empty columns for users to enter in data, and what I want is to have any data entered into those columns be saved back to the database when the window is closed. That way the linq query will still work when I load the application back up again. I'm not entirely sure how to do this or what to put in my Window_Closing event. I've searched nearly every web article and thread on this and none of them have helped me with my particular issue. Specifically I am trying to update the DeductionInfo Table. This is my Window_Loaded event where I have my linq query that loads the data:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Loads queries from each of the designated data tables in BSI_Test
var customerQuery =
(from customer in testEntity.Customers
from deduction in testEntity.DeductionInfoes.DefaultIfEmpty()
join job in testEntity.Jobs
on customer.CID equals job.CID
join claim in testEntity.Claims
on job.JID equals claim.JID
select new DataProperties
{
Customer_Name = customer.CName,
Job_Name = job.JName,
Claim_No = claim.CLNumber,
Check_No = deduction.checkNo,
Check_Date = deduction.checkDate
})
.OrderBy(c => c.Customer_Name);
//Populates the Telerik data grid with data.
gridView.ItemsSource = customerQuery.ToList();
}
This is what I tried in my Window_Closing event which didn't seem to work, and I was wondering if anyone could help me understand how to do this:
DataTable ds = new DataTable();
public void Window_Closing(object sender, CancelEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source = databaseserver; Database = database; User ID = sampleUsername; Password = SamplePassword; Integrated Security = False;");
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM DeductionInfo", con);
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
gridView.ItemsSource = dt;
con.Close();
}
The DeductionInfo table is null by the way, since this data will be used to fill it up.
Am not shure how to do this. Am litle confused, in my project c# winforms am using MVP pattern for deskotp application.
I have datagridview where i show products gorup. Database query for selecting products group is stored in model and that method for selecting return DataTable. Next, presenter call that model function for selecting and pass it to view. In view i put that DataTable in BindingSource and in gridview as DataSource i pass binding source.
This work good but what when i try to add new row in grid and try to save that new row?
What if i want to edit existing row and update that record to database.
If i want to create/update record from database i need to access to adapter and call update. Problem is becouse my adapter is in model not in view.
Am not shure how to from view access to adapter and dataset to model.
Check my code for selecting:
Model:
public DataTable SelectAll()
{
using (MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.ConnectionString))
{
try
{
conn.Open();
string query = "SELECT Naziv, Opis FROM grupe";
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
dt = new DataTable();
ds = new DataSet();
adapter.Fill(ds, "grupe");
dt = ds.Tables["grupe"];
}
conn.Close();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
return dt;
}
Presenter:
public DataTable SelectAll()
{
return _model.SelectAll();
}
View:
private void GrupeArtikala_Load(object sender, EventArgs e)
{
bs = new BindingSource();
bs.DataSource = _presenter.SelectAll();
groupDataGridView.DataSource = bs;
}
So now when i want to save changes to database i need to access to model database adapter but i dont know how.
private void saveToolStripButton_Click(object sender, EventArgs e)
{
changes = ds.GetChanges(); // DatSet changes is in model but i must access here but dont know how
if (changes != null)
{
int updatedRows = dataAdapter.Update(changes); // Adapter is in model and i need him here
ds.AcceptChanges();
}
}
Am not shure how to connect this to model to avoid mixing database queries in view forms.
Anyone can give me example to do this.
If I understand correctly, you need to call functions on objects belonging to your model, but you don't want your view to have a reference to your model. Is that right? If so, you could follow the pattern you used with the SelectAll function:
bs.DataSource = _presenter.SelectAll();
You are calling _presenter.SelectAll in the view, but ultimately getting the returned value from the model. So to call ds.GetChanges in your view, you could add a GetDataSetChanges function to your presenter:
public DataSet GetDataSetChanges()
{
return _model.GetDataSetChanges();
}
Same thing for calling update on your adapter. Add a function to the presenter:
public int UpdateAdapter(DataSet dataSet)
{
return _model.UpdateAdapter(dataSet);
}
I am attempting to build a simple application that allows me to interact with a MySQL database I have set up. I can add records just fine; however, I cannot get them to display. I am simply presented with a blank datagrid control.
It could be something simple, but I have tried different approaches, searched online, and messed with it longer than I should have - to no avail. I have a feeling the issue might lie in my lack of understanding the DataGrid control. Any help is sincerely appreciated.
The Select method from the Database Connection class:
public DataTable Select(string tableName)
{
string query = "SELECT * FROM " + tableName;
this.Open();
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
this.Close();
return dataSet.Tables[0];
}
The following is a portion of the code for the window (called View) containing the datagrid. The table name is passed to it from the main window upon the click of a button.
public View()
{
InitializeComponent();
}
public View(string table)
{
this.table = table;
InitializeComponent();
}
private void windowLoad(object sender, RoutedEventArgs e)
{
DatabaseConnection myConnection = new DatabaseConnection();
dataGrid.DataContext = myConnection.Select(table).DefaultView;
}
I'm trying to create a two-datagridview Master-Detail form to display the results of an SQL statement, but appear to have an added complication in that the two results I want to display are from the same table: I want just the IDs to appear in the top grid, and then detail from the rest of the table about the same ID to appear in the bottom grid. If I'm using the wrong method, then could someone please point me in the wrong direction?
My current problem is that the code gets to the DataRelation Rel = new DataRelation.... and displays the form (with both DataGrids blank) at that point, rather than executing the rest of the code.
I've pasted the full version below:
private void Form1_Load(object sender, EventArgs e)
{
SpContain.Panel1.Controls.Add(masterDataGridView);
SpContain.Panel2.Controls.Add(detailsDataGridView);
masterDataGridView.DataSource = masterBindingSource;
detailsDataGridView.DataSource = detailsBindingSource;
GetData();
}
private void GetData()
{
string ConnStr = "Server=TradarUAT\\uattradar; Integrated Security=SSPI; Initial Catalog=TradeFiles;";
SqlConnection Conn = new SqlConnection(ConnStr);
DataSet Data = new DataSet();
Data.Locale = System.Globalization.CultureInfo.InvariantCulture;
SqlDataAdapter masterDataAdapter = new SqlDataAdapter("Select MasterReference from [TradeFiles].[dbo].[OMG-Rejects] GROUP BY MasterReference", Conn);
masterDataAdapter.Fill(Data, "[TradeFiles].[dbo].[OMG-Rejects]");
SqlDataAdapter detailDataAdapter = new SqlDataAdapter("Select ImportedDT,TypeIndicator,FileNumber,MasterReference,ClientAlocRef,VersionNumber,DateTimeStamp,ErrorID,ErrorKey,ErrorTxt,ErrorParamType,ErrorParamValue from [TradeFiles].[dbo].[OMG-Rejects]", Conn);
detailDataAdapter.Fill(Data, "[TradeFiles].[dbo].[OMG-Rejects]");
DataRelation Rel = new DataRelation("RejectDetail",
Data.Tables[0].Columns["MasterReference"], Data.Tables[1].Columns["MasterReference"]);
Code stops executing on the above line
Data.Relations.Add(Rel);
masterBindingSource.DataSource = Data;
masterBindingSource.DataMember = "[TradeFiles].[dbo].[OMG-Rejects]";
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "RejectDetail";
}
Managed to solve this by creating a view on the SQL server that mimicked the first select statement I was trying to acheive. Then I just referenced the view in the masterDataAdapter, and retrieved the rest of the information from the underlying table in the detailDataAdapter.