GridView Table 1 related to Table 2

蹲街弑〆低调 提交于 2020-01-11 10:36:48

问题


Sorry I know Title is really confusing but I couldn't figure out what exactly to put down.

Basically I created a Grid View which queries database and displays data. It works perfectly, no complain, however what I have right now is,

but what I want is,

Question: I am not sure how can I do this, can someone just point me out in right direction please ?

I think I will going to use nested gridviews.


回答1:


Try to change your SELECT Query like below... It will you to get the Expected Result...

SQL Fiddle : http://www.sqlfiddle.com/#!3/00b5f/15

I have named the Table as Fruits

SELECT CrateTitle,CrateDescription,CrateID,
stuff(
(
    SELECT ','+ [FruitTitle] FROM fruits WHERE CrateID = t.CrateID FOR XML path('')
),1,1,'') Types_of_Fruits_in_Crate
FROM (SELECT DISTINCT CrateTitle,CrateDescription,CrateID FROM fruits )t

OR

CREATE a PROC

*Place this Query in that Proc*

*Call that Proc*

*assign that Result set to GridView*

You can Assign he Stored Proc Result set to GridView by using the Below Code :

        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection("Your Connection String");
        try
        {
            connection.Open();
            string spName = "YOURStoredProcudureName";


            SqlCommand sqlCmd = new SqlCommand(spName, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
            sqlCmd.CommandType = CommandType.StoredProcedure;


            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                //display the DataTable to a Data control like GridView for example
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }



回答2:


This is more an sql (or whatever langue your database engine uses) problem than a c# problem although one solution from c# would be (though it may be a bit of extra work) to use a html literal to draw you table at run time

the other option would be to change your sql but without more information i can't say if you could perhaps use a group by on changeID or a pivot table



来源:https://stackoverflow.com/questions/16217674/gridview-table-1-related-to-table-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!